Resumable Wait

An agent that stays running just to wait for a review, an approval, or another job burns compute doing nothing. Yet if a worker simply writes "waiting for review" and exits, nobody may have been asked — and the board can sit calmly on "waiting" for days while nothing moves.

Resumable Wait turns waiting into a durable contract stored in the hub. A job may enter waiting only by naming what it needs, which supplier owes the next move, which hub-visible resume event restarts it, when it falls overdue, and which independent recoverer steps in if that event never arrives.

Group Continuity
Also known as Suspend and Resume, Interrupt and Resume, Wait for Callback
Core rule Never park a job with a text label — bind it to supplier, event, deadline, and recoverer
Defines records Wait

Why "waiting" as a status label fails silently

Multi-agent workflows pause all the time — waiting for a legal sign-off, a human decision, an independent review, an upstream task to finish, or a shared resource to free up. Ending the worker session during a long pause is smart economics. The problem is how naive systems represent the pause.

When a worker merely sets a status field to "waiting for review" and shuts down, three things go wrong at once: the ask may never have been delivered to anyone, no clock detects if the other party goes silent, and the status board displays the exact same calm badge for an active review as for an orphaned job. "Waiting" is just a word the worker wrote on its way out the door.

Resumable Wait replaces prose status labels with three structural rules enforced by the hub:

  1. Atomic park-and-ask. Storing the Wait, flipping the job to waiting, and queuing the request to the named supplier happen together in one transaction.
  2. Proof of receipt plus a separate recoverer. The supplier must confirm receipt within minutes (acknowledged_at), and a distinct recoverer (never the supplier) is alerted automatically if confirmation or delivery misses its deadline.
  3. Event-driven automatic restart. When the declared resume_event arrives for the named target, the hub closes the wait once and restarts the job from its checkpoint without disturbing the requester.

Why forbid the supplier from being its own recoverer? Because the whole point of a recoverer is to catch a supplier that crashed, went offline, or dropped the request. Naming the same party for both fields turns every supplier outage into a silent deadlock.

Bare "waiting" label Worker says "waiting for review" Session exits to save compute No supplier is ever notified No confirmation; no due time ticking Board calmly says "waiting" Looks identical to an active review Work sits orphaned for days Human must ask if anything is moving Resumable Wait Worker opens a durable Wait Names supplier, event, due time, recoverer Hub requests & confirms supplier Worker exits cleanly; 0 idle compute Resume event or due-time sweep Late confirmation or result alerts recoverer Hub restarts job automatically Continues from checkpoint; requester calm
A bare "waiting" label cannot distinguish active work from an unrequested or abandoned task. Recording supplier, confirmation, resume event, and recoverer turns every pause into an observable, self-resuming hub record.

Architecture and participants

Every Wait links one paused Job (from Durable Job) to two distinct Party records (from Orchestrator-Workers): the Supplier who produces the needed outcome and the Recoverer who intervenes if anything runs late. The Hub owns all three lifecycle duties: opening waits with cycle prevention, matching incoming events to resume jobs once, and sweeping overdue waits.

Worker A Opens wait; resumes later Supplier Confirms & emits event Recoverer Handles overdue waits Hub coordination duties Open & cycle check Blocks duplicates & cycles Request & event Sends ask; resumes once Due-time sweep Flags unconfirmed & late Wait record open / overdue / resumed / canceled Job record At most 1 active wait; state = waiting
Worker A opens the wait and exits; the hub delivers the request to the supplier, matches the eventual resume event to wake the job once, and alerts the recoverer if confirmation or delivery misses its deadline.
Worker A
Opens a Wait when its job cannot continue, saves a checkpoint, and ends its session. When the hub restarts it, it resumes directly from that checkpoint with the event payload.
Supplier
The party expected to act — a checker, another worker, or a human answerer. Confirms receipt of the request and later emits the event that satisfies the wait. Does not need to know which worker to wake.
Recoverer
The party notified when confirmation or delivery is overdue — usually the lead agent, and never the supplier. May renew a confirmed wait (up to a limit) or cancel and replace it.
Hub
Persists Wait records, blocks duplicate active waits and wait cycles, dispatches supplier asks via an outbox, matches events idempotently, and runs the due-time sweep.
Wait
Durable record of one pause of one job, holding needs, resume_event, target (subject_id or resource_key), confirmation time, due time, and state (open, overdue, resumed, or canceled).

Execution flow

Toggle between the normal flow — where the supplier confirms receipt, Worker A frees its session, and the resume event restarts the job automatically — and the overdue recovery path — where Supplier A disappears, the recoverer switches to Supplier B, and Supplier A's late result is safely ignored.

Worker A Hub Supplier Recoverer 1. Open wait (needs review, due 12:00) 2. Store Wait & set Job waiting Checks no active wait, no cycle, supplier != recoverer 3. Deliver review request to Supplier 4. Confirm receipt (acknowledged_at) 5. Worker A ends session cleanly Zero idle compute while waiting 6. Emit resume event (finding.recorded) 7. Match Wait: resumed & Job working Recoverer & requester never disturbed 8. Restart Worker A from checkpoint + finding

Once the supplier confirms receipt, Worker A shuts down cleanly with zero idle compute. When the declared resume event arrives, the hub marks the wait resumed and restarts Worker A from its checkpoint without asking the requester or lead agent.

Already-happened events: When opening a wait, a production hub checks whether the awaited record has already reached the target state (for instance, a review landed seconds earlier) so a job never waits for an event that already fired.

Concrete examples

Resumable Wait applies whenever a job pauses for an external party or event that takes minutes, hours, or days — across legal reviews, procurement approvals, research pipelines, and engineering workflows.

Example 1 — Legal sign-off on a vendor renewal packet

No code or unit tests
Job
Assemble a supplier renewal packet after legal counsel approves two liability edits.
Wait
Worker A drafts the redlines, saves a checkpoint, and opens a Wait naming Legal Counsel as supplier, the Lead agent as recoverer, question.answered on the sign-off question as resume_event, and a 24-hour due_at. Worker A then exits.
Confirmation
Legal's intake queue confirms receipt within two minutes. The status board shows exactly who holds the ball and when the sign-off is due.
Resume
Next morning, Legal submits its answer. The hub matches question.answered to the open wait, transitions the job back to working, and restarts Worker A from its checkpoint to produce the final packet.

Example 2 — Invoice export PR 212 review

Software engineering
Job
Finish the invoice export change after an independent checker reviews pull request 212.
Wait
At 10:00 a.m. Worker A opens a Wait (resume_event: "finding.recorded", subject_id: "job_invoice_export", supplier: checker_a, recoverer: lead_1, due 12:00 p.m.). checker_a confirms at 10:01 a.m. and Worker A ends its session.
Failure
At 10:20 a.m. checker_a's host shuts down. At 12:00 p.m. the hub marks the wait overdue and notifies lead_1, who cancels Wait 1 and opens Wait 2 naming checker_b.
Resolution
checker_b approves PR 212 at 12:40 p.m., closing Wait 2 and restarting Worker A. When checker_a comes back at 1:15 p.m. and emits a late finding, the hub ignores it — restarting nothing.

What this pattern is NOT — Short retries, silent crashes, or passive alerts

Negative example
Scenario
A 3-second retry after an API rate limit, a worker that froze without saying why, or a requester who just wants an email when a deployment finishes.
Why skip it
Brief retries belong in-process without parking the job. An unexpected stall belongs to Progress Heartbeat. And watching an external condition only to notify a human (without restarting a job) belongs to Condition Monitor.

When to use and when to skip

Use Resumable Wait when

  • A job cannot continue until another party acts — with an answer, a review, a resource release, or another job's result.
  • The pause can outlast the worker session, making idle compute wasteful.
  • The hub can observe the concrete event that ends the wait.
  • Resuming the work is already covered by the requester's existing approval.

Skip it when

  • The worker stopped unexpectedly without opening a wait — use Progress Heartbeat.
  • The pause lasts only seconds (such as backoff on an API rate limit).
  • Someone intentionally parked the job indefinitely so nothing should automatically restart it.
  • The goal is only to notify a human when a condition trips — use Condition Monitor.

Data model and hub invariants

Resumable Wait defines one table — waits — referencing jobs (Durable Job), two rows in parties (Orchestrator-Workers), and either an awaited record (subject_id) or a leased resource (resource_key from Resource Lease).

Wait PK id FK job_id needs FK supplier_id FK recoverer_id resume_event FK subject_id? resource_key? opened_at acknowledged_at? due_at renewals state ended_at? end_note? Job PK id state (waiting while open) Party PK id supplier != recoverer Awaited record PK id (Question / Job / Monitor; null for lease) n at most 1 active 1 n supplier_id 1 recoverer_id 1 n subject_id (XOR key) 1? Durable Job defines Job; Orchestrator-Workers defines Party; lease waits use resource_key instead of subject_id
A Job may accumulate many Wait rows over its lifetime, but at most one may remain open or overdue at a time.

Table: waits

Column Postgres type Nullability Notes
id uuid NOT NULL, PK Unique identifier for this wait.
job_id uuid NOT NULL, FK References jobs(id); partial unique index enforces at most one active wait per job.
needs text NOT NULL One-sentence statement sent to the supplier and shown on the status board.
supplier_id uuid NOT NULL, FK References parties(id); party expected to produce the event.
recoverer_id uuid NOT NULL, FK References parties(id); CHECK (recoverer_id <> supplier_id).
resume_event text NOT NULL Event type: question.answered, finding.recorded, job.done, lease.released, or monitor.fired.
subject_id uuid NULLABLE, FK ID of the awaited Question, Job, or Monitor; NULL when waiting on lease.released.
resource_key text NULLABLE Leased resource key; filled if and only if resume_event = 'lease.released'.
opened_at timestamptz NOT NULL Time the hub stored the wait and queued the supplier request.
acknowledged_at timestamptz NULLABLE Time the supplier confirmed receipt; NULL until confirmed.
due_at timestamptz NOT NULL Deadline after which the wait transitions to overdue.
renewals integer NOT NULL Number of times the recoverer extended due_at; starts at 0.
state text NOT NULL CHECK (state IN ('open', 'overdue', 'resumed', 'canceled')).
ended_at timestamptz NULLABLE Set atomically when state becomes resumed or canceled.
end_note text NULLABLE One-sentence event summary (on resume) or cancellation reason.

Eight hub invariants

  1. 01
    At most one active wait per job, synchronized with job state Database constraint

    A partial unique index on waits(job_id) WHERE state IN ('open', 'overdue') enforces a single active wait per job (hub guard: job_already_waits). The hub flips jobs.state to and from waiting in the same transaction.

  2. 02
    Recoverer can never be the supplier Database constraint

    CHECK (recoverer_id <> supplier_id) — enforced in hub code as recoverer_is_the_supplier — prevents a single downed party from hiding its own outage.

  3. 03
    Wait names exactly one target (subject_id XOR resource_key) Database constraint

    A CHECK constraint guarantees lease.released waits set resource_key with null subject_id, while every other wait sets subject_id with null resource_key (hub guard: invalid_wait_target).

  4. 04
    Job waits never form a cycle Hub guard

    When opening a job.done wait, the hub follows the chain of active job.done waits starting at subject_id and rejects any path leading back to job_id with jobs_wait_on_each_other.

  5. 05
    Missing confirmation or passed due time alerts the recoverer Hub guard

    The due-time sweep marks an open wait overdue and notifies recoverer_id if acknowledged_at is still empty 5 minutes after opened_at, or once due_at passes.

  6. 06
    Only the recoverer may renew or cancel an overdue wait, up to the renewal cap Hub guard

    renew and cancel reject other actors with only_recoverer_may_act, closed waits with wait_not_active, unconfirmed waits with supplier_never_confirmed, and renewals past the configured cap with renewal_limit_reached.

  7. 07
    Events resume an active wait once and verify the supplier on findings Hub guard

    handle_event matches only open or overdue waits on event type and target — plus supplier_id == event.by_id for finding.recorded — then sets resumed once. Ended waits never change again.

  8. 08
    Change propagation is the sole non-recoverer cancellation path Hub guard

    When a request spec changes and stops or redoes a job, Change Propagation cancels its active wait (by_change = true) and records the spec change in end_note.

Reference implementation

The complete wait lifecycle — opening with cycle detection, confirmation, event matching, due-time sweeps, bounded renewals, and cancellation — in Lean, TypeScript, Python, and Elixir.

-- Hub guards for Resumable Wait (enforced in code, never in prompts)
import Std.Data.HashMap
open Std (HashMap)

inductive ResumeEvent where
  | questionAnswered | findingRecorded | jobDone | leaseReleased | monitorFired
  deriving Repr, BEq, DecidableEq

inductive WaitState where
  | open | overdue | resumed | canceled
  deriving Repr, BEq, DecidableEq

inductive JobState where
  | working | waiting | done
  deriving Repr, BEq, DecidableEq

structure Job where
  id : String
  assigneeId : String
  state : JobState
  deriving Repr

structure Wait where
  id : String
  jobId : String
  needs : String
  supplierId : String
  recovererId : String
  resumeEvent : ResumeEvent
  subjectId : Option String := none
  resourceKey : Option String := none
  openedAtSec : Nat
  acknowledgedAtSec : Option Nat := none
  dueAtSec : Nat
  renewals : Nat := 0
  state : WaitState := .open
  endedAtSec : Option Nat := none
  endNote : Option String := none
  deriving Repr

structure HubEvent where
  type : ResumeEvent
  subjectId : Option String := none
  resourceKey : Option String := none
  byId : Option String := none
  summary : String
  deriving Repr

structure OutboxMessage where
  to : String
  kind : String
  payload : String
  deriving Repr

inductive HubError where
  | recovererIsTheSupplier | jobAlreadyWaits | invalidWaitTarget | jobsWaitOnEachOther
  | unknownJob | unknownWait | waitNotActive | onlyRecovererMayAct
  | supplierNeverConfirmed | renewalLimitReached
  deriving Repr, BEq, DecidableEq

def confirmWithinSec : Nat := 300
def maxRenewals : Nat := 3

structure Hub where
  jobs : HashMap String Job := {}
  waits : HashMap String Wait := {}
  outbox : List OutboxMessage := []

namespace Hub

def isActive (w : Wait) : Bool := w.state == .open || w.state == .overdue

def activeForJob (hub : Hub) (jobId : String) : Option Wait :=
  hub.waits.values.find? fun w => w.jobId == jobId && isActive w

def mustGetWait (hub : Hub) (id : String) : Except HubError Wait :=
  match hub.waits[id]? with
  | some w => .ok w
  | none => .error .unknownWait

def send (hub : Hub) (to kind payload : String) : Hub :=
  { hub with outbox := hub.outbox ++ [⟨to, kind, payload⟩] }

def validTarget (w : Wait) : Bool :=
  if w.resumeEvent == .leaseReleased then w.resourceKey.isSome && w.subjectId.isNone
  else w.subjectId.isSome && w.resourceKey.isNone

-- Follow job.done waits from `cursor`; `fuel` (one step per wait) makes the walk finite.
def reaches (hub : Hub) (fuel : Nat) (cursor : String) (first : String) : Bool :=
  match fuel with
  | 0 => false
  | fuel + 1 =>
    cursor == first ||
      match hub.activeForJob cursor with
      | some { resumeEvent := .jobDone, subjectId := some next, .. } =>
        hub.reaches fuel next first
      | _ => false

def createsCycle (hub : Hub) (wait : Wait) : Bool :=
  match wait.resumeEvent, wait.subjectId with
  | .jobDone, some subject => hub.reaches (hub.waits.size + 1) subject wait.jobId
  | _, _ => false

def eventMatches (wait : Wait) (event : HubEvent) : Bool :=
  wait.resumeEvent == event.type &&
    match wait.resumeEvent with
    | .leaseReleased => wait.resourceKey == event.resourceKey
    | .findingRecorded => wait.subjectId == event.subjectId && some wait.supplierId == event.byId
    | _ => wait.subjectId == event.subjectId

-- «open» quotes the name because `open` is a Lean keyword
def «open» (hub : Hub) (wait : Wait) : Except HubError Hub := do
  if wait.supplierId == wait.recovererId then throw .recovererIsTheSupplier
  if (hub.activeForJob wait.jobId).isSome then throw .jobAlreadyWaits
  unless validTarget wait do throw .invalidWaitTarget
  if hub.createsCycle wait then throw .jobsWaitOnEachOther
  let some job := hub.jobs[wait.jobId]? | throw .unknownJob

  let hub := { hub with
    waits := hub.waits.insert wait.id { wait with state := .open, renewals := 0 },
    jobs := hub.jobs.insert job.id { job with state := .waiting } }
  return hub.send wait.supplierId "request" wait.needs

def acknowledge (hub : Hub) (waitId : String) (atSec : Nat) : Except HubError Hub := do
  let wait ← hub.mustGetWait waitId
  unless isActive wait do throw .waitNotActive
  let updated := { wait with acknowledgedAtSec := some atSec }
  return { hub with waits := hub.waits.insert waitId updated }

def renew (hub : Hub) (waitId actorId : String) (newDueAtSec : Nat) : Except HubError Hub := do
  let wait ← hub.mustGetWait waitId
  unless wait.recovererId == actorId do throw .onlyRecovererMayAct
  unless wait.state == .overdue do throw .waitNotActive
  if wait.acknowledgedAtSec.isNone then throw .supplierNeverConfirmed
  if wait.renewals >= maxRenewals then throw .renewalLimitReached

  let updated :=
    { wait with dueAtSec := newDueAtSec, renewals := wait.renewals + 1, state := .open }
  return { hub with waits := hub.waits.insert waitId updated }

-- Put a job back to work if it was waiting.
def resumeJob (hub : Hub) (jobId : String) : Hub :=
  { hub with jobs := hub.jobs.modify jobId fun j =>
      if j.state == .waiting then { j with state := .working } else j }

def cancel (hub : Hub) (waitId actorId reason : String) (atSec : Nat)
    (byChange : Bool := false) : Except HubError Hub := do
  let wait ← hub.mustGetWait waitId
  unless isActive wait do throw .waitNotActive
  unless byChange || wait.recovererId == actorId do throw .onlyRecovererMayAct

  let updated :=
    { wait with state := .canceled, endedAtSec := some atSec, endNote := some reason }
  return { hub with waits := hub.waits.insert waitId updated }.resumeJob wait.jobId

-- Returns how many waits the event resumed, and the new hub.
def handleEvent (hub : Hub) (event : HubEvent) (atSec : Nat) : Nat × Hub :=
  let hits := hub.waits.values.filter fun w => isActive w && eventMatches w event
  let hub := hits.foldl (init := hub) fun acc wait =>
    let updated := { wait with
      state := .resumed, endedAtSec := some atSec, endNote := some event.summary }
    let acc := { acc with waits := acc.waits.insert wait.id updated }
    match acc.jobs[wait.jobId]? with
    | some job =>
      { acc with jobs := acc.jobs.insert job.id { job with state := .working } }
        |>.send job.assigneeId "restart" event.summary
    | none => acc
  (hits.length, hub)

def isLate (wait : Wait) (nowSec : Nat) : Bool :=
  let unconfirmed := wait.acknowledgedAtSec.isNone && nowSec - wait.openedAtSec > confirmWithinSec
  unconfirmed || nowSec > wait.dueAtSec

-- Returns the ids of the waits it escalated, and the new hub.
def sweep (hub : Hub) (nowSec : Nat) : List String × Hub :=
  let late := hub.waits.values.filter fun w => w.state == .open && isLate w nowSec
  let hub := late.foldl (init := hub) fun acc wait =>
    { acc with waits := acc.waits.insert wait.id { wait with state := .overdue } }
      |>.send wait.recovererId "overdue" wait.needs
  (late.map (·.id), hub)

-- A wait whose supplier is also its recoverer is always refused.
theorem open_rejects_self_recovery (hub : Hub) (w : Wait) (h : w.supplierId = w.recovererId) :
    hub.«open» w = .error .recovererIsTheSupplier := by
  simp [«open», h]; rfl

end Hub

Overdue recovery and stale-event trace

Walking Example 2 (invoice export PR 212 review) through these transitions shows supplier confirmation, overdue escalation, clean supplier replacement, and automatic rejection of the replaced checker's late finding:

Execution trace: Example 2 (invoice export PR 212 review)
1. hub.open({ id: "wait_pr_212", jobId: "job_invoice_export",
     supplierId: "checker_a", recovererId: "lead_1",
     resumeEvent: "finding.recorded", subjectId: "job_invoice_export", dueAt: "12:00Z" })
   -> ok (job_invoice_export = waiting; outbox -> checker_a)

2. hub.acknowledge("wait_pr_212", "10:01Z")
   -> ok (acknowledged_at recorded; worker_a exits session cleanly)

3. # 10:20Z: checker_a machine shuts down; noon passes with no finding
   hub.sweep("12:00:01Z")
   -> overdue (wait_pr_212 = overdue; outbox -> lead_1)

4. hub.cancel("wait_pr_212", "lead_1", "Reassigned to checker_b", "12:03Z")
   hub.open({ id: "wait_pr_212_b", jobId: "job_invoice_export",
     supplierId: "checker_b", recovererId: "lead_1",
     resumeEvent: "finding.recorded", subjectId: "job_invoice_export", dueAt: "14:00Z" })
   hub.acknowledge("wait_pr_212_b", "12:04Z")
   -> ok (wait_pr_212_b active on checker_b)

5. hub.handleEvent({ type: "finding.recorded", subjectId: "job_invoice_export",
     byId: "checker_b", summary: "PR 212 approved" }, "12:40Z")
   -> resumed (wait_pr_212_b = resumed; job_invoice_export = working; restart worker_a)

6. hub.handleEvent({ type: "finding.recorded", subjectId: "job_invoice_export",
     byId: "checker_a", summary: "Late review" }, "13:15Z")
   -> no matching active wait (ignored; restarts nothing)

Tradeoffs and practical guidance

Resumable Wait keeps asynchronous pipelines moving without burning idle compute, while introducing three honest tradeoffs:

  • More structure upfront than "waiting": the worker must specify a real, hub-observable event and target instead of freeform text; agents under pressure may try to pick vague events unless the hub validates allowed event types.
  • Due times require tuning: short deadlines create noisy escalations for the recoverer, while overly generous deadlines delay spotting a dead supplier.
  • Resumption acts on prior intent: if the requester revised the request while the job slept, restarting blindly could pursue obsolete work unless Change Propagation reviews open waits on spec edits.

Practical implementation notes

  • Write the wait and supplier ask via an outbox in one transaction: if the hub crashes after committing the wait row, the outbox guarantees the supplier still receives the request.
  • Check current state before parking: when opening a wait, inspect the awaited record first — if the answer or finding already arrived, return it immediately instead of parking forever.
  • Require confirmation from the supplier itself: an HTTP 202 from a message broker proves only that a queue accepted the bytes, not that the receiving agent or person has the ask.
  • Keep event delivery idempotent and self-healing: apply resume updates with WHERE state IN ('open', 'overdue') to ignore duplicate events, and run a periodic reconciliation pass against awaited records in case an event was dropped.
  • Restart from hub records, not the old session: the worker that opened the wait may have been reassigned; always wake the job's current assignee from its latest saved checkpoint.

Known uses and related patterns

  • LangGraph interrupt() and resume: pauses a graph node, persists thread state, and resumes when a caller supplies a value in a Command (leaving deadlines and recovery policy to the hosting application).
  • AWS Step Functions callback task tokens: pauses a workflow step until an external system calls back with the task token and payload, pairing with heartbeat or task timeouts for failure handling.
  • Azure Durable Functions external events: lets a long-lived orchestration race a named external event against a durable timer, resuming automatically on whichever arrives first.
  • Agent2Agent (A2A) input-required state: lets an agent pause a task with a message describing what it needs so a client can resume the same task ID later.
  • Volgenic: tracks at most one open wait per work item with typed wait kinds, deadlines, and automated supervisor recovery steps, and resumes capacity-paused sessions automatically when model capacity reopens.
  • Classic messaging relatives: combines Hohpe & Woolf's Correlation Identifier (matching resume_event + target to one wait) with Dead Letter Channel (routing overdue waits to an independent recoverer).

Related patterns

  • Progress Heartbeat — detects a worker that stalled without saying so, whereas Resumable Wait governs a job that parked on purpose.
  • Condition Monitor — watches an external condition to alert the requester, and can emit monitor.fired events that wake a Resumable Wait.
  • Durable Job — defines the Job and Checkpoint from which a resumed worker continues.
  • Self-Contained Question & Tracked Answer — structure human asks and bind answers that emit question.answered.
  • Resource Lease — produces lease.released events keyed by resource_key.
  • Change Propagation — audits and cancels open waits built on superseded spec versions.
  • Derived Status Board — computes exactly whom each request is waiting on directly from active Wait rows.