On this page
A release agent asks a deployment controller to revert deploy-412 to rev-17. The controller writes job-1 to disk and transmits a confirmation, then the TCP link drops before that packet arrives. From the caller's side, all that arrives is a silent timeout.
Treating that timeout as proof that nothing ran queues a duplicate revert on top of job-1, while reporting success misleads operators when work is at most queued. Reliable runtimes preserve uncertainty until host code inspects live remote state, gate high-impact writes behind durable human approvals, and bound retries and failovers deterministically.
Gate actions by blast radius and undo cost
Treat every model tool call as an untrusted proposal: JSON schema validation checks syntax only, never caller authorization or whether a read-only question ("What happened to deploy-412?") permits a production write.[1][2] Sort tool calls in host code outside the prompt along blast radius and undo cost:
| Risk tier | Action class | Examples | Runtime behavior |
|---|---|---|---|
Read-only (auto) | Zero mutation | get_deploy, git_diff, read_logs | Validate scope and run automatically |
Reversible write (single_review) | Live impact, fast rollback | Canary shift (<=25%), feature flag, revert | Checkpoint and pause for one reviewer |
Irreversible / wide (dual_review or deny) | Data loss or wide blast | drop_table, root key rotation, >25% jump | Require dual sign-off with short expiry, or deny |
Pause and resume durably with human-in-the-loop checkpoints
Human review runs on minutes or hours, so holding an open coroutine in RAM fails on the first pod restart. Durable human-in-the-loop workflows follow four persistent phases:
- Checkpoint and pause: Persist thread state, a canonical SHA-256 payload digest (RFC 8785 JCS key sorting), expected target revision, stable operation key, and expiry timestamp, then exit the worker cleanly.[3]
- Scoped decision: An authenticated reviewer (
reviewer != requester) rejects, edits into a new version/digest, or approves the exact pending version and digest while viewing host-verified parameter diffs separated from untrusted model summaries or ticket text.[4] - Atomic decision and outbox commit: Inside one
BEGIN IMMEDIATEtransaction, conditionally updatestatus = 'pending' -> 'authorized'(WHERE version = ? AND digest = ? AND expires_at > ?) and insert anoutboxresume token so crashes never orphan approvals and concurrent clicks hit a conflict.[5] - Idempotent resume and live check: On resume, verify the token, digest, expiry, and live target revision (compare-and-swap) before dispatching the side effect.[6]
In LangGraph, a SQLite or PostgreSQL checkpointer saves state before interrupt() frees the worker and Command(resume=...) reloads it.[7][8][9] In Temporal, workflow.wait_condition(...) pauses durably while @workflow.update validates approvals before mutating history.[10][11]
from dataclasses import dataclass
import hashlib
import json
import sqlite3
@dataclass(frozen=True)
class ActionProposal:
tool: str
stage: str
params: dict
reversible: bool
def classify_tier(p: ActionProposal) -> str:
if p.tool in {"get_deploy", "git_diff", "read_logs"}:
return "auto"
if p.tool == "drop_table":
return "deny" if p.stage == "production" else "dual_review"
if not p.reversible or p.params.get("traffic_percent", 0) > 25:
return "dual_review"
return "single_review"
def payload_digest(params: dict) -> str:
canonical = json.dumps(params, sort_keys=True, separators=(",", ":")).encode()
return hashlib.sha256(canonical).hexdigest()[:16]
conn = sqlite3.connect(":memory:", isolation_level=None)
conn.executescript("""
CREATE TABLE checkpoints (
approval_id TEXT PRIMARY KEY, version INT NOT NULL, requester TEXT NOT NULL,
digest TEXT NOT NULL, expected_rev INT NOT NULL, op_key TEXT NOT NULL,
status TEXT NOT NULL, expires_at INT NOT NULL, reviewer TEXT
);
CREATE TABLE outbox (message_key TEXT PRIMARY KEY, approval_id TEXT NOT NULL, op_key TEXT NOT NULL);
""")
def pause_for_approval(aid: str, requester: str, params: dict, expected_rev: int, op_key: str, expires_at: int) -> str:
dig = payload_digest(params)
conn.execute("INSERT INTO checkpoints VALUES (?, 1, ?, ?, ?, ?, 'pending', ?, NULL)",
(aid, requester, dig, expected_rev, op_key, expires_at))
return dig
def approve_atomic(aid: str, version: int, dig: str, reviewer: str, now: int) -> str:
conn.execute("BEGIN IMMEDIATE")
try:
row = conn.execute("SELECT requester FROM checkpoints WHERE approval_id = ?", (aid,)).fetchone()
if not row or row[0] == reviewer:
conn.execute("ROLLBACK")
return "self_approval_forbidden"
cur = conn.execute(
"UPDATE checkpoints SET status='authorized', reviewer=? WHERE approval_id=? AND version=? AND digest=? AND status='pending' AND expires_at>?",
(reviewer, aid, version, dig, now),
)
if cur.rowcount != 1:
conn.execute("ROLLBACK")
return "conflict_or_expired"
op_key = conn.execute("SELECT op_key FROM checkpoints WHERE approval_id=?", (aid,)).fetchone()[0]
conn.execute("INSERT INTO outbox VALUES (?, ?, ?)", (f"{aid}:v{version}", aid, op_key))
conn.execute("COMMIT")
return "authorized_and_queued"
except Exception:
conn.execute("ROLLBACK")
raise
def resume_and_execute(aid: str, params: dict, live_rev: int, now: int) -> str:
row = conn.execute("SELECT digest, expected_rev, op_key, status, expires_at FROM checkpoints WHERE approval_id=?", (aid,)).fetchone()
if not row or row[3] != "authorized":
return "not_authorized"
if now >= row[4]:
return "grant_expired"
if payload_digest(params) != row[0]:
return "digest_mismatch"
if live_rev != row[1]:
return f"stale_revision(expected={row[1]}, live={live_rev})"
return f"dispatched:{row[2]}"
for prop in [
ActionProposal("get_deploy", "production", {"id": "deploy-412"}, True),
ActionProposal("promote_model", "canary", {"model": "reranker-v17", "traffic_percent": 25}, True),
ActionProposal("drop_table", "production", {"table": "orders"}, False),
]:
print(f"tier({prop.tool}) -> {classify_tier(prop)}")
canary = {"model": "reranker-v17", "traffic_percent": 25}
dig = pause_for_approval("apr-17", "deploy-bot", canary, expected_rev=41, op_key="op-canary-17", expires_at=1200)print("self-approve:", approve_atomic("apr-17", 1, dig, "deploy-bot", now=1000))
print("lead approve:", approve_atomic("apr-17", 1, dig, "release-lead", now=1000))
print("duplicate click:", approve_atomic("apr-17", 1, dig, "other-lead", now=1001))
print("tampered resume:", resume_and_execute("apr-17", {**canary, "traffic_percent": 100}, live_rev=41, now=1050))
print("drifted rev resume:", resume_and_execute("apr-17", canary, live_rev=42, now=1050))
print("clean resume:", resume_and_execute("apr-17", canary, live_rev=41, now=1050))tier(get_deploy) -> auto
tier(promote_model) -> single_review
tier(drop_table) -> deny
self-approve: self_approval_forbidden
lead approve: authorized_and_queued
duplicate click: conflict_or_expired
tampered resume: digest_mismatch
drifted rev resume: stale_revision(expected=41, live=42)
clean resume: dispatched:op-canary-17Every guard in that output prevents a distinct production outage: self-approval is rejected, a second concurrent reviewer click receives a conflict, modifying traffic_percent from 25 to 100 after sign-off fails digest verification, and an emergency cluster patch moving revision 41 to 42 stops the resumed worker from overwriting the newer fix.
Classify failures and reconcile uncertain writes with stable keys
Once an approved action enters execution, failures split across three distinct stages:
| Observed symptom | Failing stage | Confirmed state | Safe next action |
|---|---|---|---|
| Invalid arguments or unknown tool | Proposal check | Never invoked | Return diagnostic to model and revalidate retry |
| Permission denied or expired grant | Authorization check | Unauthorized | Halt and request fresh scoped approval |
Read timeout or HTTP 503 | Transport layer | State unread | Retry read with jittered backoff and hard deadline |
| Write timeout or dropped socket | Remote commit | Outcome unknown | Query operation key or replay unchanged idempotently |
Controller returns queued | Async queue | Enqueued only | Poll worker status or report queued (never completed) |
An idempotent write produces the exact same persistent side effect whether executed once or replayed after dropped confirmations. That guarantee requires server-side coordination: persist one stable logical operation key (rb-412-1) before dialing the network, rotate only per-attempt transport trace IDs (att-9f2c), and write both the side effect and operation key inside one atomic database transaction.[12][5]
import json
import sqlite3
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
from threading import Barrier
class KeyConflict(Exception):
pass
class Controller:
def __init__(self, db_path: Path):
self.db_path = db_path
with closing(sqlite3.connect(db_path)) as db, db:
db.executescript("""
CREATE TABLE IF NOT EXISTS jobs (id INTEGER PRIMARY KEY, payload TEXT NOT NULL, state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS operations (op_key TEXT PRIMARY KEY, payload TEXT NOT NULL, job_id INTEGER NOT NULL REFERENCES jobs(id));
""")
def enqueue(self, op_key: str, deploy_id: str, revision: str, fault: str | None = None) -> str:
payload = json.dumps({"deploy_id": deploy_id, "revision": revision}, sort_keys=True)
with closing(sqlite3.connect(self.db_path)) as db, db:
db.execute("BEGIN IMMEDIATE")
existing = db.execute("SELECT payload, job_id FROM operations WHERE op_key = ?", (op_key,)).fetchone()
if existing:
if existing[0] != payload:
raise KeyConflict("operation key already bound to different arguments")
return f"job-{existing[1]}"
job_id = db.execute("INSERT INTO jobs(payload, state) VALUES (?, 'queued')", (payload,)).lastrowid
db.execute("INSERT INTO operations VALUES (?, ?, ?)", (op_key, payload, job_id))
if fault == "before_commit":
raise TimeoutError("link dropped before commit")
if fault == "after_commit":
raise TimeoutError("reply dropped after commit")
return f"job-{job_id}"
def lookup(self, op_key: str) -> tuple[str, str] | None:
with closing(sqlite3.connect(self.db_path)) as db:
row = db.execute("SELECT jobs.id, jobs.state FROM operations JOIN jobs ON jobs.id = operations.job_id WHERE op_key = ?", (op_key,)).fetchone()
return None if row is None else (f"job-{row[0]}", row[1])
def job_count(self) -> int:
with closing(sqlite3.connect(self.db_path)) as db:
return db.execute("SELECT COUNT(*) FROM jobs").fetchone()[0]
with TemporaryDirectory() as directory:
ctrl = Controller(Path(directory) / "controller.sqlite")
try:
ctrl.enqueue("rb-412-1", "deploy-412", "rev-17", fault="after_commit")
except TimeoutError:
print("client saw: outcome unknown")
ctrl = Controller(Path(directory) / "controller.sqlite")
print("reconciled:", ctrl.lookup("rb-412-1"))
print("same-key replay:", ctrl.enqueue("rb-412-1", "deploy-412", "rev-17"))
try:
ctrl.enqueue("rb-412-1", "deploy-412", "rev-16")
except KeyConflict as exc:
print("rejected:", exc)
try:
ctrl.enqueue("rb-413-1", "deploy-413", "rev-17", fault="before_commit")
except TimeoutError:
pass
assert ctrl.lookup("rb-413-1") is None
start = Barrier(2)
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda _: (start.wait(5), ctrl.enqueue("rb-414-1", "deploy-414", "rev-17"))[1], range(2)))
print("concurrent race:", results, "| total jobs:", ctrl.job_count())client saw: outcome unknown
reconciled: ('job-1', 'queued')
same-key replay: job-1
rejected: operation key already bound to different arguments
concurrent race: ['job-2', 'job-2'] | total jobs: 2
Check each downstream API's retention rules: Stripe's v1 layer caches both successes and 500 responses per idempotency key and prunes keys after 24 hours, while eventually consistent read replicas can hide fresh commits.[13] Likewise, Temporal Activity retries still require idempotent destinations if a worker crashes right after a remote call commits, and Saga compensation is always a new forward operation (uncordoning a Kubernetes node permits future scheduling without restoring evicted pods) that needs its own operation key.[14][15][16][17]
Retry reads with jittered backoff, progress checks, and hard deadlines
For safe read-only calls (GET /runs/deploy-412), a budget of 3 attempts means 1 initial call plus at most 2 retries. Fixed sleeps align failing workers into synchronized load spikes; exponential backoff with full jitter spreads retries uniformly across the delay window (for zero-indexed failure , base delay , and cap ):[18]
When an upstream returns HTTP 429 or 503 with Retry-After, add capped jitter on top of Retry-After rather than taking max(retry_after, jitter) (which collapses every client onto the exact same timestamp whenever retry_after exceeds the jitter cap), and abort immediately if the combined sleep exceeds the remaining caller deadline.[19] Watch out for stacked retries across SDKs and schema-repair wrappers (two 3-attempt layers allow wire sends); enforce one outer wall-clock deadline and cumulative spend budget.[20]
import random
from dataclasses import dataclass, field
class TransientReadError(Exception):
def __init__(self, msg: str, retry_after: float = 0.0):
super().__init__(msg)
self.retry_after = retry_after
class DeadlineExceeded(Exception):
pass
@dataclass
class VirtualClock:
now: float = 0.0
waits: list[float] = field(default_factory=list)
def sleep(self, seconds: float) -> None:
self.waits.append(seconds)
self.now += seconds
def retry_read(call, *, attempts: int = 3, timeout: float = 10.0, base: float = 0.2, cap: float = 2.0, clock: VirtualClock, rng: random.Random):
deadline, ceiling = clock.now + timeout, min(base, cap)
for attempt in range(attempts):
remaining = deadline - clock.now
if remaining <= 0:
raise DeadlineExceeded("caller deadline exhausted")
try:
res = call(remaining)
except TransientReadError as exc:
if attempt + 1 == attempts:
raise
delay = exc.retry_after + rng.uniform(0.0, ceiling)
if delay >= deadline - clock.now:
raise DeadlineExceeded("required wait exceeds remaining deadline") from exc
clock.sleep(delay)
ceiling = min(cap, ceiling * 2)
else:
if clock.now >= deadline:
raise DeadlineExceeded("reply arrived past deadline")
return res
clock, calls = VirtualClock(), [0]
def fetch_status(_rem: float) -> str:
calls[0] += 1
if calls[0] < 3:
raise TransientReadError("overloaded", retry_after=0.25)
return "deploy-412 failed unit-tests"
print("result:", retry_read(fetch_status, clock=clock, rng=random.Random(7)), "| waits:", [round(w, 3) for w in clock.waits])
short_clock = VirtualClock()
try:
retry_read(lambda _: (_ for _ in ()).throw(TransientReadError("rate limited", retry_after=20.0)), timeout=3.0, clock=short_clock, rng=random.Random(1))
except DeadlineExceeded as exc:
print("aborted early:", exc, "| sleeps:", len(short_clock.waits))
# Progress detection: novel paginated evidence resets stalls; identical errors trip max_stalls
seen, stalls, max_stalls = set(), 0, 2
for step, evidence in enumerate(["status-v1", "status-v1", "log-page-1", "log-page-1", "log-page-1"], 1):
stalls = 0 if evidence not in seen else stalls + 1
seen.add(evidence)
if stalls >= max_stalls:
print(f"progress guard stopped at step {step} after {stalls} consecutive stalls")
breakresult: deploy-412 failed unit-tests | waits: [0.315, 0.31]
aborted early: required wait exceeds remaining deadline | sleeps: 0
progress guard stopped at step 5 after 2 consecutive stalls
Pair stall guards (tracking novel trusted evidence tokens rather than raw tool counts, while still enforcing a hard max_calls cap and episodic notes like Reflexion[21]) with separate context-window and cumulative spend accounting. With a fixed -token system header and history tokens appended per turn across turns, cumulative input tokens grow quadratically:
Summarizing prompt history shrinks only upcoming passes and never refunds earlier turns, so reserve worst-case cost (input + max_output_tokens) before each dispatch.
Protect dependencies with generation-scoped circuit breakers
Across hundreds of concurrent sessions, per-run retries still hammer an unhealthy service. A circuit breaker passes traffic when closed, fails fast during cooldown when open, and admits one half-open probe afterward to test recovery.[22] Tag every call with the breaker's integer generation so a slow reply started under generation 4 returns to its caller without closing a newer open generation 5, and clear probe_in_flight on cancellation so recovery never wedges.
import asyncio
class CircuitOpen(Exception):
pass
class CircuitBreaker:
def __init__(self, threshold: int = 1, cooldown: float = 5.0, clock=lambda: 0.0):
self.threshold, self.cooldown, self.clock = threshold, cooldown, clock
self.state, self.failures, self.generation = "closed", 0, 0
self.opened_at, self.probe_in_flight = 0.0, False
self.lock = asyncio.Lock()
def _trip_open(self) -> None:
self.state, self.opened_at, self.probe_in_flight = "open", self.clock(), False
self.generation += 1
async def call(self, fn):
async with self.lock:
if self.state == "open":
if self.clock() - self.opened_at < self.cooldown:
raise CircuitOpen("cooldown active")
self.state = "half_open"
if self.state == "half_open" and self.probe_in_flight:
raise CircuitOpen("probe already running")
is_probe = self.state == "half_open"
if is_probe:
self.probe_in_flight = True
gen = self.generation
try:
res = await fn()
except (TimeoutError, ConnectionError):
async with self.lock:
if gen == self.generation:
self.failures += 1
if is_probe or self.failures >= self.threshold:
self._trip_open()
raise
except asyncio.CancelledError:
async with self.lock:
if gen == self.generation and is_probe:
self._trip_open()
raise
except BaseException:
async with self.lock:
if gen == self.generation and is_probe:
self.probe_in_flight = False
raise
async with self.lock:
if gen == self.generation:
if is_probe:
self.generation += 1
self.state, self.failures, self.probe_in_flight = "closed", 0, False
return res
async def demo() -> None:
now, started, release = [0.0], asyncio.Event(), asyncio.Event()
cb = CircuitBreaker(threshold=1, cooldown=5.0, clock=lambda: now[0])
async def slow_ok() -> str:
started.set(); await release.wait(); return "gen-0-data"
async def fail_timeout() -> str:
raise TimeoutError("down")
stale = asyncio.create_task(cb.call(slow_ok))
await started.wait()
try: await cb.call(fail_timeout)
except TimeoutError: pass
release.set()
assert await stale == "gen-0-data" and cb.state == "open"
print("stale gen-0 finish keeps state:", cb.state)
now[0] = 5.0; started.clear(); release.clear()
probe = asyncio.create_task(cb.call(slow_ok))
await started.wait()
probe.cancel()
try: await probe
except asyncio.CancelledError: pass
assert cb.state == "open" and not cb.probe_in_flight
now[0] = 10.0; release.set()
assert await cb.call(slow_ok) == "gen-0-data" and cb.state == "closed"
print("post-cancel recovery probe:", cb.state)
asyncio.run(demo())stale gen-0 finish keeps state: open
post-cancel recovery probe: closed
Build honest fallbacks and report outcomes transparently
When a controller stays unavailable, swapping model providers never invents live telemetry, widens permissions, or overrides caller cancellation. Enforce observation freshness in host code so recent snapshots stay dated ("job-1 was queued when checked 10s ago") while stale or missing records return "Current revert status is unavailable" and emit a compact, redacted human handoff packet (operation key, canonical payload, last verified timestamp, and pause reason).
from dataclasses import dataclass
@dataclass(frozen=True)
class Observation:
deploy_id: str
job_id: str
state: str
observed_at: int
source: str
def format_status(obs: Observation | None, *, deploy_id: str, job_id: str, now: int, max_age: int = 30) -> str:
if obs is None or (obs.deploy_id, obs.job_id) != (deploy_id, job_id):
return "Current revert status is unavailable."
if obs.source != "controller" or obs.state not in {"queued", "running", "completed", "failed"}:
return "Current revert status is unavailable."
age = now - obs.observed_at
return f"{job_id} was {obs.state} when checked {age}s ago." if 0 <= age <= max_age else "Current revert status is unavailable."
for sample in (Observation("deploy-412", "job-1", "queued", 990, "controller"),
Observation("deploy-412", "job-1", "completed", 100, "controller"), None):
print(format_status(sample, deploy_id="deploy-412", job_id="job-1", now=1000))job-1 was queued when checked 10s ago.
Current revert status is unavailable.
Current revert status is unavailable.
Finally, never collapse degraded fallbacks and human handoffs into a single "success" number. If 100 failed runs recover as 60 full completions, 12 dated degraded answers, 18 safe human handoffs, and 10 unresolved timeouts, report all four rates separately using unique runs in the denominator so reviewer workload and capability drops stay visible.