When an AI agent waits six hours for approval
Execution leases, durable human approval, and claim-time revalidation in Rails—why releasing compute while waiting is only half the problem.
During a six-hour approval wait, RubyLLM can store the question and release the worker. On resume, the host must check who is acting and what the action would do now. If the consequences have changed materially, show the difference and ask again.
My previous post covered evaluation jobs and tool approvals. Put those examples side by side and a practical question follows. When a person returns hours later, what is still waiting, and what needs to be checked again?
Consider this hypothetical case: at 09:00, an in-app assistant proposes deleting a draft newsletter campaign or activating a sequence. The app creates an approval request and pauses. The user gets pulled into meetings and does not click Approve until 15:00. In those six hours, a deploy replaced every worker process, an admin changed team roles, and a teammate edited the draft campaign into a scheduled broadcast.
That single six-hour pause actually raises four separate questions: Is any worker still running? Is the approval still valid? Who can resume it? Does the proposed action still match reality?
A worker can lose its lease without losing a user's approval. Conversely, a user can approve an operation that is no longer safe to execute. Those two failure modes look similar in a chat interface, but they belong to different state machines.
My previous post discussed 30-minute evaluation leases in ActiveAgent #614 and #715 alongside in-app tool approvals in Lewsnetter #53. Connecting those two timers is completely natural—and they are not the same clock:
- ActiveAgent's 30-minute evaluation leases guard active background scoring and replay jobs; they are not human approval deadlines.
- In RubyLLM's persisted Rails path, a waiting approval persists its question and returns, releasing ordinary execution ownership until a human answers.
- Lewsnetter #53 builds on RubyLLM's persisted questions and rechecks authorization when the user decides and when the tool runs.
- The RubyLLM AG-UI 1.0.0 adapter adds its own configurable interrupt expiry (900 seconds by default), separate from RubyLLM's execution lease.
In the design I propose, the server checks current permissions and business facts before acting. If a change alters what the person would be agreeing to, show the difference and ask again. If the action is now forbidden, stop.
If you only have a minute, this image is the whole post:
For the implementation details, start with the four-layer comparison below. The later campaign diff and test matrix are proposals for a host application.
Four clocks and three kinds of state
Half the confusion around long-lived agents comes from calling four different timers "the timeout." Before comparing frameworks, separate the clocks:
Track the active worker, the runtime’s progress limit, the approval window and the current business conditions separately. Record a human decision independently of the tool’s execution outcome.
| Clock | What it limits | Typical owner | What expiry means |
|---|---|---|---|
| Execution lease | Temporary ownership of an active execution attempt | Runtime / worker | Another attempt may be allowed to acquire ownership |
| Execution deadline / progress timeout | Duration or progress of active work | Runtime / queue / provider | Abort, interrupt, or classify the attempt as failed |
| Approval TTL | How long a human decision request may be answered or redeemed | Application / approval protocol | Reject or replace the expired request |
| Business validity | Whether the proposed operation is still appropriate now | Domain model / application | Block, recompute, or request a new approval |
A hard execution deadline limits total elapsed time. A progress timeout measures time since the last sign of progress, so a long run can remain healthy. Neither measures how long a person may consider a proposal.
A fifth concept—retention—governs audit history and storage cleanup, not permission validity. External provider conversation state and OAuth token lifetimes can also impose their own limits independently of your app's clocks.
Three orthogonal state machines
In a durable agent design, three lifecycles move independently and should never be collapsed into one column:
- Run lifecycle:
queued → executing → waiting_for_input → queued/resuming → executing → terminal. - Approval lifecycle:
pending → approved | declined | expired | cancelled | superseded. A human decision can be persisted before continuation work is scheduled or claimed. - Tool execution lifecycle:
not_started → claimed → running → succeeded | failed | outcome_uncertain.
Three practical rules follow immediately from separating them: never collapse approved into executed; never treat a parked waiting_for_input record as a crashed running job; and when a pending or approved request is superseded, keep the original decision intact for audit and issue a fresh request with a new identity rather than mutating the original consent. Nor should you use an unrelated record's updated_at as a proxy for authorization freshness.
What the 30-minute ActiveAgent leases actually do
Two of my ActiveAgent PRs added fixed leases to evaluation jobs. Each lease covers a specific piece of active work.
ActiveAgent's 30-minute leases in #614 and #715 guard active evaluation judge and replay jobs with owner tokens and fenced writes; they are not human-approval timers, and fencing protects database writes rather than remote billing.
Judge scoring: ActiveAgent #614
In ActiveAgent #614 (merged October 30, 2026; diff), duplicate evaluation judge jobs could both invoke the scoring LLM because an earlier timestamp-based claim was not enough to keep overlapping deliveries apart.
The fix introduced migration 030 (add_evaluation_scoring_leases, with a pre-migration fallback) and a time-limited owner token. A worker acquires the lease in a short database write, runs the LLM scoring request outside any database lock, and guards both success and failure writes with its owner token so a displaced worker cannot clobber its successor's result.
One recovery detail in the merged PR matters: when a duplicate delivery sees a live lease, you should reschedule it for lease expiry rather than silently dropping it. If the original process died hard and the queue already redelivered the job once, dropping the duplicate strands the work—expiry by itself never enqueues a retry.
The lease window is a fixed 30 minutes. A scoring call that genuinely runs longer can still be invoked again after 30 minutes. In the PR, 61 focused test runs (484 assertions) passed, while PostgreSQL/MySQL and live queue/provider concurrency were explicitly noted as unverified. The architectural lesson is narrow and clear: token fencing protects database writes, not provider billing or remote exactly-once execution.
Replay fan-out: ActiveAgent #715
ActiveAgent #715 (merged November 17, 2026; diff) solved a sibling problem in ScenarioEvaluationRunner#replay_scenario!. Previously, the runner checked whether a replay result existed, executed the agent, and only then locked the run to store the result. Two competing deliveries could both call the provider and tools before one threw its work away.
#715 added a per-scenario/provider/model claim token and 30-minute REPLAY_LEASE_DURATION inside scores["_fan_out"]["replays"], acquired under update_fan_out_state! while keeping external work outside the transaction. A duplicate delivery hitting a live owner reschedules with wait_until: the lease expiry and rechecks whether a result has already been stored; an expired claim can be taken over, and result storage, release, and failure bookkeeping are fenced by owner token. The PR describes regression tests for duplicate delivery, expiry, late owners, and judge-enqueue errors. Its mutation checks are reported separately from the committed tests.
As the PR itself notes, a replay that exceeds 30 minutes can still overlap, and a worker that dies after the provider responds but before persisting can replay the provider call. Because replay evaluation can invoke tools, evals need controlled fixtures or side-effect-free tools. Either way, none of this is an approval scheduler.
Atomic claims are not automatically leases
Two other merged PRs I wrote in ActiveAgent draw the line even more sharply:
- ActiveAgent #664 (diff) adds a conditional transition to claim a pending agent run before execution. That prevents duplicate deliveries from both starting the same run, but by itself it does not add an expiring lease or dead-worker recovery for ordinary runs.
- ActiveAgent #713 (diff) claims a pending evaluation run before sequential or fanned-out replay—a separate guard from the pair-level replay and judge leases above.
Keep three distinct protections separate in your head: claim before work (stops duplicate starts), lease expiry (permits a new attempt to take over), and token fencing after work (stops late owners from overwriting newer state).
ActiveAgent: checkpoint and resume, not a sleeping job
ActiveAgent's actual human-in-the-loop pause mechanism lives in a different part of the codebase—upstream work by other ActiveAgent contributors starting from issue #539 and implemented across PR #550 and PR #556 (diff).
ActiveAgent's upstream checkpoint flow (#550/#556) parks a serialized checkpoint instead of sleeping a worker, and #672 makes waiting runs atomically cancellable—leaving persistence and approval expiry policy to the host.
Rather than parking a thread or sleeping a background job, the framework emits an InputRequest and a serialized checkpoint capturing the conversation and waiting tool calls (including which calls require approval). Answers are passed into execution state rather than leaked into model-authored tool arguments. When the human responds:
Generation#resume_now(checkpoint:, answers:)reconstructs the action's tools and instructions and dispatches the resumed calls with the answer in execution state.Generation#resume_later(checkpoint:, answers:, **job_options)validates the answers and enqueuesGenerationJobwithresume:. Notably, it rejects answers to secret input requests because queue arguments may be stored unencrypted—turning off parameter logging does not encrypt your queue table.
One nuance matters if you are wiring this into production: a checkpoint serialization API is not automatically durable storage in every host. You still need to verify which run-backed paths persist the checkpoint for you and which require your application to store, version, and restore it across deploys.
Cancellation while waiting: ActiveAgent #672
Because waiting for human input is a first-class lifecycle state, it has to be cancellable safely. In ActiveAgent #672 (my own PR, merged November 6, 2026; diff), run cancellation performs a conditional update restricted to pending, running, and awaiting_input. If the transition wins, pending input requests are cancelled in the same transaction; otherwise a reload reflects the terminal state so a stale browser tab or delayed job cannot overwrite a completed run.
So what happens in ActiveAgent after six hours? A properly persisted checkpoint can sit parked without holding a worker—the cited PRs do not impose a universal 30-minute deadline on human input. Whether it still succeeds six hours later depends on the host's persistence, expiry policy, deploy compatibility, and whether the actor and tools remain valid. (Racing approval against cancellation and duplicate resume jobs are separate concurrency edges that still deserve host-level tests; #672 fixes cancellation transitions, not every resume race.)
RubyLLM: the persisted chat owns the continuation
The 2.2.0 release introduced the upstream feature. For the behavior below I used the 2.2.3 tool guide and background-job guide.
In RubyLLM's documented Rails integration, pausing for approval releases active execution ownership while persisting pending questions; the 60-second lease (renewed every 15s) belongs only to active execution, and interrupted tools are not blindly replayed.
The durable approval path
In RubyLLM's persisted Rails integration (acts_as_chat), a tool declares requires_approval or pauses interactively for input. Questions and answers live on persisted tool-call records:
chat.pending_questionssurfaces waiting questions without instantiating tools or opening MCP connections;chat.waiting?tells you the chat is parked.askandcompletereturn once human input is required, releasing ordinary execution ownership. (In a multi-tool round, other eligible calls may run before the turn parks, so do not assume every tool in the round freezes instantaneously.)- One process can create the question, a web request can record the answer, and a third worker after a deployment can load the chat via its agent class and continue. That durability belongs to the persisted Rails integration—not to a plain in-memory Ruby chat object.
chat.answer(question_id, ...)records a first decision, whereasapproveis intentionally able to revise an earlier decline. For ordinary approval UIs, stick to first-decision semantics unless changing minds is an explicit product feature. Declining a tool call that is already running can raiseRubyLLM::ToolCallRunningError, and sending another user message while tool calls are unresolved raisesRubyLLM::PendingToolCallsErrorunless your host explicitly declines or supersedes them first.
For interactive tools that call ask mid-method, code before the question can run again on resume—keep that prefix free of side effects. If the tool asks a different question on replay, RubyLLM can re-prompt rather than applying an old answer to a mismatched question. Useful safeguard, yes—comprehensive domain-state validation, no.
The 60-second lease belongs to active work
In RubyLLM 2.2.3, the ordinary persisted execution claim lasts one minute and the worker attempts renewal every 15 seconds. Normal return clears the claim. A live process can also lose it if renewals fail or the run stops making progress. The guide documents an exception for calls made inside an application transaction: renewal from a separate connection cannot see the claim, so the lease uses max_run_time. Run these methods outside your own transaction.
Operational details matter here: seeing a claim_token in the database does not by itself mean a worker is alive (the documented running? predicate checks lease validity); heartbeat renewals consume database connections and depend on synchronized clocks; and under SQLite write contention, renewal behavior deserves its own testing rather than assumptions carried over from PostgreSQL.
Six hours later—and what if a worker crashes mid-mutation?
Put those two halves together and the six-hour question has a clean answer at the RubyLLM layer: when the chat parks for approval, it returns and clears its active claim. No six-hour heartbeat runs. Six hours later—assuming the host still allows the approval and the persisted records remain compatible—a continuation attempt acquires a fresh execution claim and proceeds. The cited 2.2.3 docs do not define a general approval TTL, though that is never a guarantee that every provider session or host integration accepts arbitrarily old approvals.
RubyLLM persists questions, decisions, and execution ownership; it does not verify that your underlying ActiveRecord target, recipient list, or authorization rules stayed unchanged over those six hours, nor does it render a business-state diff. That belongs to your host application.
And what if a worker crashes after sending an email or calling Stripe, but before persisting the tool result? RubyLLM's documented interrupted-tool handling deliberately avoids blindly replaying a call that may already have caused a side effect, instead signaling to the model that the tool may have partially executed. That is the opposite of eval replay in ActiveAgent #715—and rightly so. Still, suppressing retries does not produce distributed exactly-once execution: you still need a stable domain idempotency key, an operation ledger, external status reconciliation, and human escalation when outcomes remain uncertain.
Lewsnetter: a real Rails product on top of the runtime
Frameworks give you primitives; real products expose the seams between layers. Here is what happened when I wired approvals, scopes, and claim-time revalidation into Lewsnetter, an open-source Rails email-marketing app (all PRs below are my own merged contributions).
Lewsnetter separates server-side approval (#53), OAuth scopes (#35), MCP host hints (#54), send claims (#61), and claim-time business revalidation (#80)—showing both what already works and where a generic semantic-diff UI is still new design.
In-app tool approvals in the chat channel: PR #53
Lewsnetter #53 (merged November 16, 2026; diff) gates destructive operations and sequence activation behind server-side approval in the tool adapter (Chats::ToolAdapter#requires_approval?), describing the proposed operation and affected record rather than showing an opaque tool name.
The lockfile at the merge of #53 pins RubyLLM 2.2.0. The in-app chat uses RubyLLM's persisted tool-call questions, rebuilding pending approval cards on reconnect. In ChatChannel, the decision handler (#decide) runs still_authorized?—crucial on a long-lived ActionCable websocket whose subscription-time permissions can go stale—locates the pending question by ID, records approvals via @chat.answer(question) (preserving first-decision semantics) and declines via @chat.decline, broadcasts the outcome, rebuilds tool context, and calls @chat.complete through run_turn. Tool ability is checked again when the tool actually invokes.
Notice two boundaries of #53 so we don't romanticize it: first, resumption runs directly inside the channel rather than enqueuing a durable ActiveJob continuation (so a disconnect or restart mid-resumption is a different failure mode than a job-backed worker); second, #53 adds no wall-clock approval TTL of its own, and opposing approve/decline race broadcasts still warrant dedicated UI-sync verification even when database first-decision storage is safe.
Approval and authorization in PR #35 and PR #54
Two adjacent PRs keep permission layers from bleeding into each other:
- Lewsnetter #35 (diff) enforces
mcp:readOAuth scope on the server at the tool boundary. Human approval can never grant a write tool to a read-only token. - Lewsnetter #54 (diff) adds read-only and destructive MCP tool annotations for external hosts. Annotations are client hints—never server-side authorization—and external MCP clients follow a separate dispatch and consent surface from the in-app chat gate.
Claim-time revalidation: the deeper analogy in PR #80
The clearest real-world lesson for stale approvals actually came from scheduled email sends, not chat. Lewsnetter #61 (diff) added an atomic claim before a campaign begins sending so competing workers cannot double-send. Then issue #79 surfaced the harder bug: a campaign was legitimately scheduled when the job was enqueued, then postponed, cancelled, or changed before the queued job ran.
Lewsnetter #80 (merged November 22, 2026; diff) fixed that by tagging scheduler-origin jobs (from_scheduler: true) and rechecking scheduled status, due time, and segment or all-subscriber confirmation under the claim lock before sending.
Be careful with the attribution here: #80 fixes scheduled campaign sends; it does not implement generic stale-approval detection or a semantic-diff UI. It is the exact structural analogy, though. A human approval recorded at 09:00 is also a previously valid decision sitting idle until execution time. If that draft newsletter becomes a scheduled production broadcast before 15:00, team membership and tool ability can both still pass while the real-world consequence of delete_campaign(id: 42) has completely changed.
RubyLLM AG-UI: when an interrupt expires
The RubyLLM AG-UI 1.0.0 adapter sets an interrupt expiry of 900 seconds (15 minutes) by default. The run accepts an expires_in: override. This is a setting of this Ruby implementation.
The RubyLLM AG-UI 1.0.0 adapter adds an explicit interrupt TTL (900s default), single-redemption decision recording, and a server-held argument digest—separate from RubyLLM's execution lease, though expired interrupts still require host reconciliation and current-state checks.
At default TTL, a six-hour-old AG-UI interrupt is rejected on resume. First redemption records the decision and competing submissions are rejected by the store; cancellation records a denial; and the server checks the original pending tool-call ID and its arguments before applying the decision. Even with a longer expires_in:, two boundaries remain the host's job:
- Layer reconciliation: rejecting an expired AG-UI interrupt can leave an underlying RubyLLM pending tool call waiting unless your host explicitly declines, cancels, or replaces it—and you must ensure no direct host endpoint bypasses the interrupt TTL. Survival across restarts also depends on using a durable interrupt store rather than a process-local one.
- Same arguments, different meaning: the adapter compares the digest of the host’s currently pending call with the digest saved at interrupt creation. The same arguments still match after campaign #42 becomes scheduled.
Comparing the four layers without conflating them
Compact comparison of ActiveAgent, RubyLLM Rails (2.2.3 docs), Lewsnetter #53/#80, and AG-UI (1.0.0 security guide), scoped strictly to the cited versions and PRs.
| Aspect | ActiveAgent | RubyLLM Rails (2.2.3 docs) | Lewsnetter #53 / #80 | AG-UI (1.0.0 guide) |
|---|---|---|---|---|
| Primary scope | Agent framework & evals | Persisted chat & tool runtime | Product approvals & domain guards | Interaction protocol & interrupt store |
| Durable pause | Checkpoint + InputRequest (host persistence varies) | Questions on tool-call records | Uses persisted RubyLLM chat | Interrupt store (durability depends on store) |
| Worker during wait | No sleeping worker in checkpoint flow | No active completion worker | No waiting completion call | Interrupt parks interaction |
| Execution lease | Fixed 30m in eval judge/replay (#614/#715) | 60s active claims, renewed every 15s | Underlying RubyLLM | Underlying runtime (separate from TTL) |
| Approval TTL | Not established by cited PRs | Not established by cited docs | None added in #53 | 900s default, configurable |
| Auth after wait | Host responsibility | Host responsibility | Re-checked in channel & tool | Host responsibility |
| Domain freshness | Host responsibility | Host responsibility | #80 analogy for scheduled sends | Argument digest only; domain state is host's job |
| Semantic diff & reapproval | Not established by cited PRs | Not established by cited docs | Not established by #53/#80 | Not established; host policy & UI needed |
The actual design challenge: stale intent
Suppose the same person, with the same role, approves the same tool arguments six hours later. Has the operation itself changed? The campaign example shows why an argument check can pass even when fresh consent is warranted.
In the proposed design, Automatically recheck authorization, decision binding, and domain preconditions on the server; if material facts changed and the new action is still permitted, supersede the request, show the meaningful before/after diff, and require fresh consent; guard the final mutation against TOCTOU.
Everything in this section is a proposed Rails design combining the lessons above—not an assertion that any cited library already implements it end-to-end. First, look at the nine things that can go sideways while an approval sits idle:
| Change while waiting | Why checking approval alone fails | Proposed treatment |
|---|---|---|
| User loses team access | Decision was once legitimate; current actor is unauthorized | Reject at decision and execution |
| Target record changes materially | Original action's meaning or blast radius shifted | Supersede and request fresh approval |
| Tool arguments are modified | Consent does not cover the altered call | Bind decision to server-side canonical intent |
| Tool semantics change in a deploy | Same name and args can behave differently | Version tool semantics or invalidate on breaking deploy |
| Another actor already did the work | Re-running can duplicate an irreversible side effect | Reconcile existing outcome with idempotency |
| Approval arrives past TTL | Stale browser tab still displays an active button | Atomically reject expired decision and refresh UI |
| Decision saved, job never enqueued | Durable consent exists, but work is stranded | Transactional outbox or recoverable poller |
| Worker loses lease mid-mutation | Remote effect may already have occurred | Fence local writes; reconcile remote status |
| Provider / MCP session expires | Local approval is valid, remote call cannot resume | Re-establish safe state or re-propose; never silently substitute |
An approval envelope, not a boolean flag
To detect stale intent and explain it to a human, store immutable proposal identity separately from mutable decision and execution state (illustrative schema, not RubyLLM's or ActiveAgent's tables):
approval_requests
id, tenant_id, requester_id, run_id, tool_call_id
tool_name, tool_semantic_version, canonical_arguments_digest
target_type, target_id, expected_lock_version (optional)
proposal_snapshot_ref, semantic_fingerprint, fingerprint_schema_version
materiality_policy_version, effect_summary, decision_snapshot_ref (optional)
status, requested_at, expires_at (nullable)
decided_by_id, decided_at, decision_reason
superseded_by_id, consumed_at
invalidation_reason, invalidated_at (preserve original decision)
execution_attempts
id, run_id, tool_call_id, owner_token, lease_expires_at
started_at, finished_at, outcome
stable_operation_key, external_reference
Notice why both a semantic_fingerprint and a redacted proposal_snapshot_ref exist. A hash digest alone can tell your code that something changed, but it cannot tell a human what changed. Conversely, storing a full unredacted copy of sensitive records creates a data-leak hazard. Store only the minimum decision-relevant facts, scope snapshot reads to the currently authorized viewer, and keep secrets out of client payloads and logs.
In this proposed Rails design, the approval and outbox share a transactional database. The submitted revision identifies the proposal the person saw. For an approval, the host also compares the proposal with current decision-relevant facts under a lock or equivalent version check. A material change invalidates that proposal and requires a fresh review.
# Web request. The server accepts only :approve or :decline.
ApprovalRequest.transaction do
approval.lock!
authorize_decision!(actor, approval)
next approval.decision if approval.decided? # return the stored winner
approval.require_pending_and_unexpired!(now: Time.current)
approval.check_displayed_revision!(submitted_revision)
if decision == :approve
check = approval.check_current_intent_under_lock(actor)
next approval.supersede_with!(check.new_proposal) if check.needs_fresh_consent?
next approval.record_noop! if check.already_satisfied?
check.require_permitted_and_current!
end
approval.require_pending_and_unexpired!(now: Time.current)
approval.record_first_decision!(decision, actor: actor, now: Time.current)
OutboxEvent.create!(kind: "decision_recorded", subject_id: approval.id)
end
# The outbox has a unique index on [kind, subject_id].
# Its consumer reads the stored decision. On decline it closes the tool
# request without running it. Only an effective approval can start work.
# Continuation worker:
# 1. Acquire runtime execution claim separately.
# 2. In a short domain transaction, reload target, re-authorize, check binding,
# expiry policy, and domain preconditions, and reserve a durable operation key.
# 3. Never hold a DB lock across remote HTTP/LLM I/O.
# 4. Invoke external work with the stable operation key (and If-Match where supported).
# 5. Persist outcome under owner-token fencing; reconcile uncertain outcomes.
An after_commit enqueue leaves a crash window between database commit and queue submission. Writing the outbox event in the decision transaction makes a committed decision discoverable after a crash. A dispatcher retries delivery, and its consumer must tolerate duplicates. On a repeated or conflicting click, return the stored decision to the caller. Be equally explicit about whether your TTL governs when a decision may be submitted, when execution may start, or both—once an irreversible side effect has begun, TTL expiry is not retroactive undo.
From automatic revalidation to renewed human consent
Automatic checks and human-visible diffs operate at different boundaries and are never interchangeable:
| Boundary | Automatic server responsibility | Human-facing behavior |
|---|---|---|
| Proposal creation | Authorize visibility; capture canonical intent and decision-relevant facts from a consistent read | Show target, parameters, expected effect, scope, and conditions |
| Opening an old card | Refresh current facts and authorization; compute preliminary materiality check | Show current status, changes, expiry, and whether the card is still answerable |
| Approval submission | Authorize actor; verify request ID and displayed revision; atomically reject stale or expired consent | If materially changed, supersede and ask for fresh review—never accept a stale tab click |
| Worker claim / resume | Acquire execution claim; load authoritative policy and domain state; check binding, revocation, expiry | Surface executing, blocked, or superseded status without assuming a live browser |
| Final mutation | Re-verify and reserve/mutate under the relevant lock or conditional write | If state shifted again mid-flight, stop and trigger a fresh review if still permitted |
| Completion / reconciliation | Persist outcome, deduplicate events, reconcile uncertain external effects | Show what actually happened—not merely that approval succeeded earlier |
Never treat a cached UI diff, an LLM-written summary, or an earlier authorize! call as an execution guarantee. And classify changes by consequences, not blindly by updated_at or lock_version:
| Classification | Example | Policy outcome |
|---|---|---|
| Immaterial | An unrelated metadata timestamp changes; decision-relevant facts match | Continue after checks—no needless human round trip |
| Material, still permitted | Campaign #42 moved from Draft (0 recipients) to Scheduled (1,280 recipients), and policy still allows deletion | Supersede old request; create fresh proposal showing what changed |
| Forbidden or impossible | Actor lost permission, target was deleted, or policy forbids deleting scheduled campaigns | Block outright—never offer an approve button that overrides policy |
| Already satisfied | Another teammate already completed the intended operation | Reconcile or return a domain no-op—never repeat blindly |
| Unknown / unavailable | Policy service or target cannot be read, or external outcome is uncertain | Fail closed for new mutations; retry validation or reconcile |
Materiality rules should be domain-owned, deterministic, reviewable, and versioned. An LLM can help summarize a verified before/after diff in plain English, but it must never be the authority deciding authorization or materiality.
Context-aware approval UX: show the change, not just the error
Take an illustrative scenario (not observed Lewsnetter UI): at 09:00, the agent proposes delete_campaign(id: 42) on an unused draft. At 15:00, campaign #42 is scheduled for 1,280 recipients. The arguments are byte-for-byte identical, yet the risk is completely different:
| Decision-relevant field | Original proposal (09:00) | Current state (15:00) | Why it matters |
|---|---|---|---|
| Campaign | #42 | #42 | Same record ID does not mean same intent |
| Status | Draft | Scheduled | Deletion now disrupts a planned send |
| Recipient scope | 0 | 1,280 | Potential blast radius expanded |
| Record version | 7 | 9 | Technical evidence, not the primary explanation |
| Proposed consequence | Remove unused draft | Cancel & remove scheduled broadcast | Requires a new decision if policy allows it |
Instead of a cryptic 409 Conflict toast or a silent failure, show plain-language copy backed by an authoritative server proposal revision:
“This request is no longer current. Campaign #42 was a draft when deletion was proposed. It is now scheduled for 1,280 recipients. The original request cannot be used. Review the updated operation before deciding.”
If current policy allows deletion, present an explicit next step (Review updated deletion → Approve updated request / Decline) bound to a new request ID and proposal revision, keeping the original decision immutable for audit and non-redeemable. If policy forbids deleting scheduled campaigns, show the blocked explanation with no approve button. Never leak fields the viewer is no longer authorized to read, never rely on color alone to convey diffs, and make stale browser tabs reject old revisions cleanly rather than broadcasting a misleading success.
TOCTOU: the last check is part of the mutation
Even fresh approval does not end concurrency. A teammate can edit campaign #42 from version 9 to version 10 in the milliseconds between a human clicking Approve updated request and the worker executing the deletion. That is classic time-of-check/time-of-use (TOCTOU).
- Local Rails database mutations: combine fresh authorization and domain preconditions with the write in a short transaction using a concurrency strategy that matches the invariant—pessimistic locking (
with_lock) when writers coordinate on the locked row, or optimistic locking (lock_version) / conditional updates checking affected row counts. Watch out for multi-record invariants: adding 500 subscribers to a segment does not necessarily bump the parent campaign'slock_version. Protect the actual predicate (consistent lock ordering, database constraints, coordinated version counters, or serializable transactions with retries where supported), and test PostgreSQL and SQLite isolation assumptions separately. - External API mutations: never hold a Rails database transaction across network I/O. Reserve a durable operation identity under validated local conditions, then send a conditional request (such as an HTTP
If-MatchETag or resource version) alongside a stable idempotency key when the downstream API supports both. Remember that an idempotency key prevents duplicate effects—it does not enforce freshness. Where a remote API lacks conditional writes, disclose that residual uncertainty instead of pretending a local check guarantees remote immutability.
Approval as a conditional grant
Put simply, an approval is permission from a specified actor for a specified proposed effect under specified conditions, within a defined policy and time scope. It does not grant authority the actor lacks, freeze a business object, or confer runtime ownership. The runtime helps persist and resume the decision; your domain owns the conditions.
A lease establishes who may execute. Authorization establishes what is permitted. Approval captures human intent. Revalidation establishes whether that intent still applies.
Concurrency, recovery, and observability: the tests that matter
An architecture diagram is cheap until you try to break it with deterministic concurrency barriers and crash injection. The matrix below lists 34 proposed test invariants (proposed experiments, not newly executed benchmark results) covering everything from six-hour restarts to TOCTOU races and redacted diffs.
Turn the design into verifiable guarantees with deterministic barriers across preview, decision, claim, and commit—testing lease expiry, opposing decisions, revoked membership, material vs. immaterial diffs, TOCTOU, and uncertain external outcomes (T01–T34).
Start with one test on each side of the approval: revoke the actor’s permission before execution (T11), then change the recipient set while the actor stays authorized (T27). The first should block the mutation. The second should detect a material change even if the parent row version stays the same.
- Pin versions and adapters: record exact gem lockfiles, Rails version, database (test PostgreSQL and SQLite separately—do not generalize from one), and queue adapter. Use fake LLM providers and mock downstream APIs, counting calls received by the fake independently of stored tool results.
- Use barriers instead of sleeps: place deterministic synchronization barriers at preview, decision persistence, worker claim, and final domain commit, mutating target state or permissions at each barrier across separate database connections/processes.
- Mutation-test your own guards: temporarily delete the conditional claim, owner-token fence, expiry check, authorization recheck, semantic fingerprint, or domain lock—confirm the matching test actually fails.
Open the full 34-scenario verification matrix (T01–T34)
| ID | Scenario | Invariant to verify | Target |
|---|---|---|---|
T01 | Pause, advance 6h, resume in new process | Durable pending input; no worker held by this turn; one continuation if still permitted | RubyLLM / AA / Lewsnetter |
T02 | Normal pause vs. hard kill mid-persistence | Normal claim cleared; dead active claim expires; pending state recovered | RubyLLM |
T03 | Duplicate delivery while active claim valid | No competing active attempt inside claim window | RubyLLM / AA #614/#715 |
T04 | Fixed eval lease expires while work still runs | Takeover allowed; stale DB writes fenced; external overlap acknowledged | AA #614/#715 |
T05 | Two simultaneous approval submissions | One effective decision; at most one permitted mutation | RubyLLM / Lewsnetter / AG-UI |
T06 | Approve vs. decline concurrently | Consistent stored winner and UI; no mutation on effective decline | Lewsnetter / RubyLLM / AG-UI |
T07 | Approve vs. cancel concurrently | No impossible terminal state; clear cutoff once mutation starts | AA #672 / host |
T08 | Submission right at TTL boundary | Atomic expiry/decision rule with explicit inclusive/exclusive edge | AG-UI / host |
T09 | Expired interrupt leaves backend question pending | Explicit reconciliation or replacement; no unintended execution | AG-UI + RubyLLM |
T10 | Team membership revoked after pause | Decision and mutation authorization reject stale actor | Lewsnetter #53 |
T11 | Permission revoked after answer, before tool run | No unauthorized side effect | Lewsnetter / host |
T12 | Target content, status, or recipients change | Material change invalidates approval or triggers fresh confirmation | Proposed host (#80 analogy) |
T13 | User sends new message while approval waits | Explicit supersession or pending-call error policy | Lewsnetter / RubyLLM |
T14 | Worker dies after external action, before DB write | No blind replay; uncertain outcome reconciled | RubyLLM + host |
T15 | Answer committed; queue enqueue fails | Work stays discoverable; recovery consumer is idempotent | Proposed outbox |
T16 | Deploy changes tool schema or checkpoint | Fail closed or migrate explicitly; no silent reinterpretation | All persisted paths |
T17 | Mixed round: one tool completes, one waits | Completed results retained; prior side effects not repeated | RubyLLM / AA |
T18 | Client disconnects and reconnects during wait | Restores durable approval and authoritative state, not stale UI | Lewsnetter / AG-UI |
T19 | Heartbeat blocked by DB contention or clock skew | Observe lease behavior and stale-owner fencing | RubyLLM |
T20 | Remote MCP approval expires at provider/session | Reject or re-propose safely; never substitute another tool call | RubyLLM remote approvals |
T21 | Trace records tool failure or denial | Distinguish requested, approved, declined, executed, failed | AA #665 / telemetry |
T22 | Only irrelevant metadata changes while waiting | No needless reapproval when semantic conditions stay valid | Proposed host |
T23 | Material, permitted change with identical args | No mutation under old consent; new request + diff + fresh approval | Proposed host / RubyLLM |
T24 | Material change makes action forbidden | No executable replacement approval and no side effect | Proposed host |
T25 | Old browser tab submits superseded revision | Stale revision rejected; new request stays undecided; accurate UI | Proposed host / AG-UI |
T26 | Domain changes again after fresh approval (TOCTOU) | Atomic domain guard fails; re-validate or re-review; no stale mutation | Proposed Rails host |
T27 | Recipient membership changes without bumping parent version | Aggregate/predicate change detected; parent version not trusted alone | Proposed Rails host |
T28 | Auth revoked between diff generation and decision/run | No unauthorized disclosure or mutation | Proposed host |
T29 | Validator dependency unavailable, then recovers | Fail closed while unknown; durable retry or visible blocked state | Proposed host |
T30 | Remote resource version changes after local reservation | Conditional request (If-Match) rejects stale write where supported | Proposed external tool |
T31 | Reapproval issued, client drops, or outbox redelivers | Old request stays non-redeemable; new request discoverable | Proposed host / AG-UI |
T32 | External op succeeds, local completion write fails | Reconcile by stable operation key—never re-ask consent as substitute | Proposed host / RubyLLM |
T33 | Diff includes fields approver cannot currently view | Redact or block display; zero leakage in UI, logs, or events | Proposed host |
T34 | Policy/materiality rule or tool semantics change on deploy | Explicit migration or invalidation; no silent consent-scope shift | Proposed host |
Observability that does not cry wolf
Correlate run_id, approval_id, tool_call_id, attempt_id, tenant, and stable_operation_key across structured logs and traces without dumping secrets or raw sensitive diffs. Track waiting approval age separately from queue latency and active execution duration. Alert on answered-but-not-resumed work and stuck active runs—never merely because a human legitimately took six hours to reply. Break out revalidation outcomes (unchanged, immaterial, material_superseded, forbidden, unavailable), stale-client conflicts, conditional-write conflicts, lease takeovers, heartbeat failures, and unresolved external outcomes.
(For capturing tool execution boundaries cleanly, ActiveAgent #665 shows why recording client-side MCP dispatch and soft errors matters alongside ordinary Ruby tool calls; extending traces to full approval-lifecycle telemetry is a natural host-level next step, not something #665 itself implements.)
Conclusion: approval is a durable decision, not a durable lock
Fixed eval leases expire on active work; durable approval pauses release compute and persist decisions separately; preserving consent over six hours requires automatic revalidation, visible diffs for material changes, and an atomic mutation boundary.
For a Rails application that parks tool calls, I would make two decisions explicit:
- Does the lease expire while an approval sits for hours? A fixed evaluation lease (#614, #715) can expire while active work is still running, which is why fencing and rescheduling exist. A normal durable approval pause (RubyLLM's persisted Rails path, ActiveAgent's persisted checkpoint flow, Lewsnetter #53) returns and relinquishes active execution ownership; a later continuation acquires a fresh claim rather than stretching a six-hour worker lease. The RubyLLM AG-UI adapter layers an explicit, configurable interrupt expiry on top.
- Do you recheck preconditions automatically, or show the approver what changed? Both. Recheck authorization, decision binding, and business preconditions automatically on the server at execution time; block forbidden actions outright; let immaterial changes pass; and when material facts shift while the action stays permitted, supersede the old consent, show a meaningful before/after diff, require fresh approval, and guard the final mutation against TOCTOU.
An agent can remember what a person approved. It must still establish whether doing it now is allowed—and whether it is still the same action.
Read this with an AI
This post is long and structured on purpose so you can walk through it with an AI or apply its design directly inside your own Rails repo. A plain Markdown copy lives at /blog/when-ai-agents-wait-for-approval.md.
A plain Markdown copy lives at /blog/when-ai-agents-wait-for-approval.md. The full post includes copyable prompts for auditing leases, approval TTL, and TOCTOU guards in your own repo.
Or paste one of these prompts into Cursor, Claude Code, or Codex:
-
Audit our approval & resume flow
Read https://www.wangyaodi.com/blog/when-ai-agents-wait-for-approval.md. Inspect how this codebase handles human-in-the-loop tool approvals, background leases, and resumption. Report (with exact file paths and lines): (1) whether compute is released during waits, (2) whether approval is conflated with authorization or execution, (3) whether business state is revalidated under a lock at mutation time, and (4) what happens if the worker crashes after an external side effect.
-
Design a semantic fingerprint & diff
Read https://www.wangyaodi.com/blog/when-ai-agents-wait-for-approval.md. For our most sensitive AI tool in this repo, propose: (1) which domain fields and aggregates belong in a semantic fingerprint, (2) which changes are immaterial vs. material vs. forbidden, (3) what plain-language before/after diff the UI should show, and (4) the exact Rails locking/conditional-update guard to close TOCTOU.
-
Write barrier concurrency tests
Read https://www.wangyaodi.com/blog/when-ai-agents-wait-for-approval.md and look at its verification matrix (T01–T34). Propose the 5 highest-value deterministic concurrency tests for our current Rails stack (PostgreSQL/SQLite + our job adapter) using synchronization barriers rather than sleeps, and show what guard each test breaks if removed.
How this post was made
I wrote this post with AI, and every post here says how it was made:
- Sources
- My merged PRs in ActiveAgent (
#614,#664,#665,#672,#713,#715) and Lewsnetter (#35,#53,#54,#61,#80); upstream ActiveAgent issues/PRs (#539,#550,#556); RubyLLM 2.2.0 release notes and 2.2.3 stable guides; AG-UI 1.0.0 security guide; Rails locking/transaction API docs; and my previous post. - Draft
- Structured from an editorial research dossier and drafted with Antigravity, including the three inline SVG diagrams, comparison tables, and share cards.
- Checks
- On 27 November 2026 Codex checked the cited GitHub PR records, Lewsnetter’s lockfile at #53, the RubyLLM 2.2.3 guides, and RubyLLM AG-UI 1.0.0 source. T01–T34 are proposed experiments.
- Original publication
- Reviewed and approved for publication by Andy Wang.
- Revision
- 1 December 2026. Revised the proposed approval example to distinguish repeat clicks, declines and approvals. The state diagram now shows where an already-completed action stops. The 34 scenarios remain a proposed test matrix.
If you spot a version drift, a misread edge case, or a cleaner Rails pattern, tell me on X and I will update this post.
References
Prior post, merged PRs across ActiveAgent and Lewsnetter, RubyLLM 2.2.x docs, AG-UI 1.0.0 guide, and Rails locking/transaction API references.
- Production AI in Rails is mostly background-job engineering (Markdown edition) — predecessor post
- ActiveAgent (my PRs): #614 (scoring leases), #664 (pending-run claim), #665 (MCP eval observation), #672 (conditional cancel of
awaiting_input), #713 (eval-run claim), #715 (replay fan-out leases) - ActiveAgent (upstream pause/resume): Issue #539, PR #550, PR #556
- RubyLLM (upstream): Tool execution guide, Durable agents guide (observed 2.2.3), v2.2.0 release, Issue #503, Issue #635
- Lewsnetter (my PRs): #35 (
mcp:readscope), #53 (in-app tool approvals), #54 (MCP annotations), #61 (campaign send claim), #80 (scheduled-send claim-time revalidation; issue #79) - RubyLLM AG-UI: Security & deployment guide (1.0.0), Approval & resume guide, repository
- Rails API docs: Optimistic locking, Pessimistic locking, Transactions