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.
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:
-
Atomic park-and-ask. Storing the
Wait, flipping the job towaiting, and queuing the request to the namedsupplierhappen together in one transaction. -
Proof of receipt plus a separate recoverer. The supplier must confirm
receipt within minutes (
acknowledged_at), and a distinctrecoverer(never the supplier) is alerted automatically if confirmation or delivery misses its deadline. -
Event-driven automatic restart. When the declared
resume_eventarrives 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.
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.
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.
Wait records, blocks duplicate active waits
and wait cycles, dispatches supplier asks via an outbox, matches events idempotently,
and runs the due-time sweep.
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.
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.
Begins after Wait 1 is open and confirmed on Supplier A with a 12:00 p.m. deadline.
When the due time passes with no finding, the hub alerts the recoverer once. The recoverer cancels Wait 1 and opens Wait 2 on Supplier B. Even when Supplier A comes back later with a late finding, the hub ignores it because Wait 1 is closed and Wait 2 named Supplier B.
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 Adrafts the redlines, saves a checkpoint, and opens aWaitnaming Legal Counsel assupplier, the Lead agent asrecoverer,question.answeredon the sign-off question asresume_event, and a 24-hourdue_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.answeredto the open wait, transitions the job back toworking, and restartsWorker Afrom 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 Aopens aWait(resume_event: "finding.recorded",subject_id: "job_invoice_export",supplier: checker_a,recoverer: lead_1, due 12:00 p.m.).checker_aconfirms 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 waitoverdueand notifieslead_1, who cancels Wait 1 and opens Wait 2 namingchecker_b. - Resolution
-
checker_bapproves PR 212 at 12:40 p.m., closing Wait 2 and restarting Worker A. Whenchecker_acomes 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).
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
-
01At 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 flipsjobs.stateto and fromwaitingin the same transaction. -
02Recoverer can never be the supplier Database constraint
CHECK (recoverer_id <> supplier_id)— enforced in hub code asrecoverer_is_the_supplier— prevents a single downed party from hiding its own outage. -
03Wait names exactly one target (subject_id XOR resource_key) Database constraint
A
CHECKconstraint guaranteeslease.releasedwaits setresource_keywith nullsubject_id, while every other wait setssubject_idwith nullresource_key(hub guard:invalid_wait_target). -
04Job waits never form a cycle Hub guard
When opening a
job.donewait, the hub follows the chain of activejob.donewaits starting atsubject_idand rejects any path leading back tojob_idwithjobs_wait_on_each_other. -
05Missing confirmation or passed due time alerts the recoverer Hub guard
The due-time sweep marks an
openwaitoverdueand notifiesrecoverer_idifacknowledged_atis still empty 5 minutes afteropened_at, or oncedue_atpasses. -
06Only the recoverer may renew or cancel an overdue wait, up to the renewal cap Hub guard
renewandcancelreject other actors withonly_recoverer_may_act, closed waits withwait_not_active, unconfirmed waits withsupplier_never_confirmed, and renewals past the configured cap withrenewal_limit_reached. -
07Events resume an active wait once and verify the supplier on findings Hub guard
handle_eventmatches onlyopenoroverduewaits on event type and target — plussupplier_id == event.by_idforfinding.recorded— then setsresumedonce. Ended waits never change again. -
08Change 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 inend_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
// Hub guards for Resumable Wait (enforced in code, never in prompts)
type ResumeEvent =
| "question.answered"
| "finding.recorded"
| "job.done"
| "lease.released"
| "monitor.fired";
type WaitState = "open" | "overdue" | "resumed" | "canceled";
interface Job {
id: string;
assigneeId: string;
state: "working" | "waiting" | "done";
}
interface Wait {
id: string;
jobId: string;
needs: string;
supplierId: string;
recovererId: string;
resumeEvent: ResumeEvent;
subjectId: string | null;
resourceKey: string | null;
openedAtSec: number;
acknowledgedAtSec: number | null;
dueAtSec: number;
renewals: number;
state: WaitState;
endedAtSec: number | null;
endNote: string | null;
}
interface HubEvent {
type: ResumeEvent;
subjectId?: string;
resourceKey?: string;
byId?: string;
summary: string;
}
const CONFIRM_WITHIN_SEC = 300;
const MAX_RENEWALS = 3;
class Hub {
private jobs = new Map<string, Job>();
private waits = new Map<string, Wait>();
public outbox: Array<{ to: string; kind: string; payload: string }> = [];
open(wait: Wait): void {
if (wait.supplierId === wait.recovererId) throw new Error("recoverer_is_the_supplier");
if (this.activeForJob(wait.jobId)) throw new Error("job_already_waits");
const isLease = wait.resumeEvent === "lease.released";
const validTarget = isLease
? wait.resourceKey !== null && wait.subjectId === null
: wait.subjectId !== null && wait.resourceKey === null;
if (!validTarget) throw new Error("invalid_wait_target");
if (this.createsCycle(wait)) throw new Error("jobs_wait_on_each_other");
const job = this.jobs.get(wait.jobId);
if (!job) throw new Error("unknown_job");
this.waits.set(wait.id, { ...wait, state: "open", renewals: 0 });
job.state = "waiting";
this.outbox.push({ to: wait.supplierId, kind: "request", payload: wait.needs });
}
acknowledge(waitId: string, atSec: number): void {
const wait = this.mustGetWait(waitId);
if (wait.state !== "open" && wait.state !== "overdue") throw new Error("wait_not_active");
wait.acknowledgedAtSec = atSec;
}
renew(waitId: string, actorId: string, newDueAtSec: number): void {
const wait = this.mustGetWait(waitId);
if (wait.recovererId !== actorId) throw new Error("only_recoverer_may_act");
if (wait.state !== "overdue") throw new Error("wait_not_active");
if (wait.acknowledgedAtSec === null) throw new Error("supplier_never_confirmed");
if (wait.renewals >= MAX_RENEWALS) throw new Error("renewal_limit_reached");
wait.dueAtSec = newDueAtSec;
wait.renewals += 1;
wait.state = "open";
}
cancel(waitId: string, actorId: string, reason: string, atSec: number, byChange = false): void {
const wait = this.mustGetWait(waitId);
if (wait.state !== "open" && wait.state !== "overdue") throw new Error("wait_not_active");
if (!byChange && wait.recovererId !== actorId) throw new Error("only_recoverer_may_act");
wait.state = "canceled";
wait.endedAtSec = atSec;
wait.endNote = reason;
const job = this.jobs.get(wait.jobId);
if (job && job.state === "waiting") job.state = "working";
}
handleEvent(event: HubEvent, atSec: number): number {
let resumedCount = 0;
for (const wait of this.waits.values()) {
if ((wait.state === "open" || wait.state === "overdue") && this.matches(wait, event)) {
wait.state = "resumed";
wait.endedAtSec = atSec;
wait.endNote = event.summary;
const job = this.jobs.get(wait.jobId)!;
job.state = "working";
this.outbox.push({ to: job.assigneeId, kind: "restart", payload: event.summary });
resumedCount += 1;
}
}
return resumedCount;
}
sweep(nowSec: number): string[] {
const escalated: string[] = [];
for (const wait of this.waits.values()) {
const unconfirmed =
wait.acknowledgedAtSec === null && nowSec - wait.openedAtSec > CONFIRM_WITHIN_SEC;
if (wait.state === "open" && (unconfirmed || nowSec > wait.dueAtSec)) {
wait.state = "overdue";
this.outbox.push({ to: wait.recovererId, kind: "overdue", payload: wait.needs });
escalated.push(wait.id);
}
}
return escalated;
}
private matches(wait: Wait, event: HubEvent): boolean {
if (wait.resumeEvent !== event.type) return false;
if (wait.resumeEvent === "lease.released") return wait.resourceKey === event.resourceKey;
if (wait.resumeEvent === "finding.recorded") {
return wait.subjectId === event.subjectId && wait.supplierId === event.byId;
}
return wait.subjectId === event.subjectId;
}
private createsCycle(wait: Wait): boolean {
if (wait.resumeEvent !== "job.done" || !wait.subjectId) return false;
let cursor: string | null = wait.subjectId;
while (cursor) {
if (cursor === wait.jobId) return true;
const next = this.activeForJob(cursor);
cursor = next && next.resumeEvent === "job.done" ? next.subjectId : null;
}
return false;
}
private activeForJob(jobId: string): Wait | undefined {
for (const w of this.waits.values()) {
if (w.jobId === jobId && (w.state === "open" || w.state === "overdue")) return w;
}
return undefined;
}
private mustGetWait(id: string): Wait {
const wait = this.waits.get(id);
if (!wait) throw new Error("unknown_wait");
return wait;
}
}
# Hub guards for Resumable Wait (enforced in code, never in prompts)
from dataclasses import dataclass
from typing import Literal, Optional
CONFIRM_WITHIN_SEC = 300
MAX_RENEWALS = 3
ResumeEvent = Literal[
"question.answered", "finding.recorded", "job.done", "lease.released", "monitor.fired"
]
WaitState = Literal["open", "overdue", "resumed", "canceled"]
@dataclass
class Job:
id: str
assignee_id: str
state: Literal["working", "waiting", "done"] = "working"
@dataclass
class Wait:
id: str
job_id: str
needs: str
supplier_id: str
recoverer_id: str
resume_event: ResumeEvent
opened_at_sec: int
due_at_sec: int
subject_id: Optional[str] = None
resource_key: Optional[str] = None
acknowledged_at_sec: Optional[int] = None
renewals: int = 0
state: WaitState = "open"
ended_at_sec: Optional[int] = None
end_note: Optional[str] = None
class HubError(Exception):
pass
class Hub:
def __init__(self) -> None:
self.jobs: dict[str, Job] = {}
self.waits: dict[str, Wait] = {}
self.outbox: list[tuple[str, str, str]] = []
def open(self, wait: Wait) -> None:
if wait.supplier_id == wait.recoverer_id:
raise HubError("recoverer_is_the_supplier")
if self._active_for_job(wait.job_id) is not None:
raise HubError("job_already_waits")
is_lease = wait.resume_event == "lease.released"
valid_target = (
(wait.resource_key is not None and wait.subject_id is None)
if is_lease
else (wait.subject_id is not None and wait.resource_key is None)
)
if not valid_target:
raise HubError("invalid_wait_target")
if self._creates_cycle(wait):
raise HubError("jobs_wait_on_each_other")
job = self.jobs.get(wait.job_id)
if job is None:
raise HubError("unknown_job")
self.waits[wait.id] = wait
job.state = "waiting"
self.outbox.append((wait.supplier_id, "request", wait.needs))
def acknowledge(self, wait_id: str, at_sec: int) -> None:
wait = self._get_wait(wait_id)
if wait.state not in ("open", "overdue"):
raise HubError("wait_not_active")
wait.acknowledged_at_sec = at_sec
def renew(self, wait_id: str, actor_id: str, new_due_at_sec: int) -> None:
wait = self._get_wait(wait_id)
if wait.recoverer_id != actor_id:
raise HubError("only_recoverer_may_act")
if wait.state != "overdue":
raise HubError("wait_not_active")
if wait.acknowledged_at_sec is None:
raise HubError("supplier_never_confirmed")
if wait.renewals >= MAX_RENEWALS:
raise HubError("renewal_limit_reached")
wait.due_at_sec = new_due_at_sec
wait.renewals += 1
wait.state = "open"
def cancel(
self, wait_id: str, actor_id: str, reason: str, at_sec: int, by_change: bool = False
) -> None:
wait = self._get_wait(wait_id)
if wait.state not in ("open", "overdue"):
raise HubError("wait_not_active")
if not by_change and wait.recoverer_id != actor_id:
raise HubError("only_recoverer_may_act")
wait.state = "canceled"
wait.ended_at_sec = at_sec
wait.end_note = reason
job = self.jobs.get(wait.job_id)
if job is not None and job.state == "waiting":
job.state = "working"
def handle_event(self, event: dict[str, str], at_sec: int) -> int:
resumed = 0
for wait in self.waits.values():
if wait.state in ("open", "overdue") and self._matches(wait, event):
wait.state = "resumed"
wait.ended_at_sec = at_sec
wait.end_note = event["summary"]
job = self.jobs[wait.job_id]
job.state = "working"
self.outbox.append((job.assignee_id, "restart", event["summary"]))
resumed += 1
return resumed
def sweep(self, now_sec: int) -> list[str]:
escalated: list[str] = []
for wait in self.waits.values():
unconfirmed = (
wait.acknowledged_at_sec is None
and now_sec - wait.opened_at_sec > CONFIRM_WITHIN_SEC
)
if wait.state == "open" and (unconfirmed or now_sec > wait.due_at_sec):
wait.state = "overdue"
self.outbox.append((wait.recoverer_id, "overdue", wait.needs))
escalated.append(wait.id)
return escalated
def _matches(self, wait: Wait, event: dict[str, str]) -> bool:
if wait.resume_event != event.get("type"):
return False
if wait.resume_event == "lease.released":
return wait.resource_key == event.get("resource_key")
if wait.resume_event == "finding.recorded":
return wait.subject_id == event.get("subject_id") and wait.supplier_id == event.get("by_id")
return wait.subject_id == event.get("subject_id")
def _creates_cycle(self, wait: Wait) -> bool:
if wait.resume_event != "job.done" or wait.subject_id is None:
return False
cursor: Optional[str] = wait.subject_id
while cursor is not None:
if cursor == wait.job_id:
return True
nxt = self._active_for_job(cursor)
cursor = nxt.subject_id if nxt and nxt.resume_event == "job.done" else None
return False
def _active_for_job(self, job_id: str) -> Optional[Wait]:
for w in self.waits.values():
if w.job_id == job_id and w.state in ("open", "overdue"):
return w
return None
def _get_wait(self, wait_id: str) -> Wait:
wait = self.waits.get(wait_id)
if wait is None:
raise HubError("unknown_wait")
return wait
# Hub guards for Resumable Wait (pure functional core)
defmodule Waits do
@confirm_within 300
@max_renewals 3
def open(state, wait) do
cond do
wait.supplier_id == wait.recoverer_id -> {:error, :recoverer_is_the_supplier}
active_for_job(state, wait.job_id) != nil -> {:error, :job_already_waits}
not valid_target?(wait) -> {:error, :invalid_wait_target}
creates_cycle?(state, wait) -> {:error, :jobs_wait_on_each_other}
not Map.has_key?(state.jobs, wait.job_id) -> {:error, :unknown_job}
true ->
{:ok,
state
|> put_in([:waits, wait.id], Map.merge(wait, %{state: :open, renewals: 0}))
|> put_in([:jobs, wait.job_id, :state], :waiting)
|> send_to(wait.supplier_id, {:request, wait.id, wait.needs})}
end
end
def acknowledge(state, wait_id, at) do
with {:ok, wait} <- fetch_wait(state, wait_id),
true <- active?(wait) || {:error, :wait_not_active} do
{:ok, put_in(state, [:waits, wait_id, :acknowledged_at], at)}
end
end
def renew(state, wait_id, actor_id, new_due_at) do
with {:ok, wait} <- fetch_wait(state, wait_id),
true <- wait.recoverer_id == actor_id || {:error, :only_recoverer_may_act},
true <- wait.state == :overdue || {:error, :wait_not_active},
true <- wait.acknowledged_at != nil || {:error, :supplier_never_confirmed},
true <- wait.renewals < @max_renewals || {:error, :renewal_limit_reached} do
updated = %{wait | due_at: new_due_at, renewals: wait.renewals + 1, state: :open}
{:ok, put_in(state, [:waits, wait_id], updated)}
end
end
def cancel(state, wait_id, actor_id, reason, at, by_change \\ false) do
with {:ok, wait} <- fetch_wait(state, wait_id),
true <- active?(wait) || {:error, :wait_not_active},
true <- (by_change or wait.recoverer_id == actor_id) || {:error, :only_recoverer_may_act} do
updated = %{wait | state: :canceled, ended_at: at, end_note: reason}
next_state =
state
|> put_in([:waits, wait_id], updated)
|> update_in([:jobs, wait.job_id], fn job ->
if job && job.state == :waiting, do: %{job | state: :working}, else: job
end)
{:ok, next_state}
end
end
def handle_event(state, %{summary: summary} = event, at) do
state.waits
|> Map.values()
|> Enum.filter(&(active?(&1) and matches?(&1, event)))
|> Enum.reduce(state, fn wait, acc ->
updated = %{wait | state: :resumed, ended_at: at, end_note: summary}
assignee = acc.jobs[wait.job_id].assignee_id
acc
|> put_in([:waits, wait.id], updated)
|> put_in([:jobs, wait.job_id, :state], :working)
|> send_to(assignee, {:restart, wait.job_id, summary})
end)
end
def sweep(state, now) do
state.waits
|> Map.values()
|> Enum.filter(&(&1.state == :open and late?(&1, now)))
|> Enum.reduce(state, fn wait, acc ->
acc
|> put_in([:waits, wait.id, :state], :overdue)
|> send_to(wait.recoverer_id, {:overdue, wait.id, wait.needs})
end)
end
defp valid_target?(%{resume_event: "lease.released", resource_key: k, subject_id: nil})
when is_binary(k),
do: true
defp valid_target?(%{resume_event: ev, resource_key: nil, subject_id: id})
when ev != "lease.released" and is_binary(id),
do: true
defp valid_target?(_), do: false
defp matches?(%{resume_event: "lease.released"} = w, %{type: "lease.released"} = e),
do: w.resource_key == e[:resource_key]
defp matches?(%{resume_event: "finding.recorded"} = w, %{type: "finding.recorded"} = e),
do: w.subject_id == e[:subject_id] and w.supplier_id == e[:by_id]
defp matches?(%{resume_event: t} = w, %{type: t} = e), do: w.subject_id == e[:subject_id]
defp matches?(_, _), do: false
defp late?(wait, now) do
unconfirmed? =
wait.acknowledged_at == nil and DateTime.diff(now, wait.opened_at) > @confirm_within
unconfirmed? or DateTime.compare(now, wait.due_at) == :gt
end
defp creates_cycle?(state, %{resume_event: "job.done", job_id: first, subject_id: next}),
do: reaches?(state, next, first)
defp creates_cycle?(_, _), do: false
defp reaches?(_, same, same), do: true
defp reaches?(state, job_id, first) do
case active_for_job(state, job_id) do
%{resume_event: "job.done", subject_id: next} -> reaches?(state, next, first)
_ -> false
end
end
defp active?(w), do: w.state in [:open, :overdue]
defp active_for_job(state, jid), do: Enum.find(Map.values(state.waits), &(&1.job_id == jid and active?(&1)))
defp fetch_wait(state, id), do: Map.fetch(state.waits, id) |> then(&if(&1 == :error, do: {:error, :unknown_wait}, else: &1))
defp send_to(state, party, msg), do: update_in(state.outbox, &[{party, msg} | &1])
end
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:
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 aCommand(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-requiredstate: 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.firedevents that wake a Resumable Wait. - Durable Job — defines the
JobandCheckpointfrom which a resumed worker continues. - Self-Contained Question & Tracked Answer — structure human asks and bind answers that emit
question.answered. - Resource Lease — produces
lease.releasedevents keyed byresource_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
Waitrows.