Durable and Asynchronous Agent Work › The worker loop
Language AI HandbookAll chapters With a new lease, a later worker can continue using the recorded step markers when the current turn ends without a terminal state. The worker checks and renews its assignment before executing a step. Intent and completion transitions also recheck the same ownership generation atomically. Completion writes group the tool result with the step marker.
PythonIn [13]Expand
LEASE_SECONDS = 5.0
MAX_TASK_ATTEMPTS = 3
def claim_task(worker_id: str, *, max_attempts: int = MAX_TASK_ATTEMPTS):
with tx() as con:
now = time.time()
available = con.execute(
"""SELECT id, kind, input, attempts, deadline, lease_epoch FROM tasks
WHERE status IN ('pending', 'running')
AND (lease_until IS NULL OR lease_until <= ?)
ORDER BY created_at, id""",
(now,),
).fetchall()
for task_id, kind, raw_input, attempts, deadline, epoch in available:
if deadline is not None and deadline <= now:
apply_terminal(con, task_id, "failed", "deadline_exceeded")
continue
if attempts >= max_attempts:
apply_terminal(con, task_id, "failed", "attempt_budget")
continue
con.execute(
"""UPDATE tasks SET status='running', lease_worker=?, lease_until=?,
lease_epoch=?, attempts=attempts+1 WHERE id=?""",
(worker_id, now + LEASE_SECONDS, epoch + 1, task_id),
)
return {
"id": task_id,
"kind": kind,
"input": json.loads(raw_input),
"attempts": attempts + 1,
"deadline": deadline,
"lease_epoch": epoch + 1,
}
return None
def renew_lease(worker_id: str, task: dict) -> bool:
with tx() as con:
now = time.time()
cur = con.execute(
"""UPDATE tasks SET lease_until=?
WHERE id=? AND status='running' AND lease_worker=?
AND lease_epoch=? AND lease_until>?""",
(
now + LEASE_SECONDS,
task["id"],
worker_id,
task["lease_epoch"],
now,
),
)
return cur.rowcount == 1renew_lease returns False if our lease has expired: another worker may have claimed the task, and we should stop writing. That's the fencing check applied at renewal. Combined with renew_lease, a well-behaved worker will exit early when fenced, minimizing wasted work.
The claim loop scans pending tasks and running tasks without a live lease. It marks expired or exhausted tasks failed and can select a remaining claimable task. In the SQLite fixture these steps share a write transaction.
Each loop turn renews the lease, folds the recorded trace, records intent, then runs one stub operation and attempts a fenced completion transaction. If the lease expires while the stub runs, that worker cannot commit the result to the task event log.
PythonIn [14]Expand
def plan_for(kind: str) -> list[dict]:
if kind == "draft_report":
return [
{
"tool": "search",
"input": {"q": "durable agent work"},
"cost": 0.01,
},
{"tool": "summarize", "input": {"style": "brief"}, "cost": 0.02},
{
"tool": "send_email",
"input": {"to": "user@example.com"},
"cost": 0.00,
},
]
if kind == "charge_customer":
return [
{
"tool": "validate_order",
"input": {"order": "ord_42"},
"cost": 0.01,
},
{
"tool": "charge_card",
"input": {"order": "ord_42", "amount": 1900},
"cost": 0.00,
},
{
"tool": "send_receipt",
"input": {"to": "user@example.com"},
"cost": 0.00,
},
]
raise ValueError(f"unknown kind {kind}")Each step has a tool name, parsed input (analogous to the JSON the model would produce in Function Calling), and a nominal cost. The runner doesn't care what the tool means; it only cares that the tool call is at the idempotent boundary.
The two plans are chosen to contrast the good case with the dangerous one. In draft_report, the only non-idempotent effect is the final send_email, so ordering is naturally safe: a crash at any earlier step can be retried freely. In charge_customer, the money-moving step charge_card is in the middle, with send_receipt after it. If the process crashes after the charge but before the receipt, a naive retry would charge the card twice. This is exactly the workflow that must lean on idempotency keys and compensation, and it is why we include it alongside the apparently-simpler report task.
The actual tool implementations are stubs. To make the demo's crashes visible, we let the caller inject a "crash after this step" instruction.
PythonIn [15]Expand
EXECUTED = [] # records every real (non-cached) tool execution; results are printed by output-only blocks
def execute_tool(tool: str, tool_input: dict) -> Any:
EXECUTED.append({"tool": tool, "input": tool_input, "t": time.time()})
if tool == "search":
return {"hits": ["a", "b", "c"]}
if tool == "summarize":
return {"summary": "durability matters"}
if tool == "send_email":
return {"ok": True, "message_id": f"msg_{uuid.uuid4().hex[:8]}"}
if tool == "validate_order":
return {"ok": True}
if tool == "charge_card":
return {"ok": True, "charge_id": f"ch_{uuid.uuid4().hex[:8]}"}
if tool == "send_receipt":
return {"ok": True}
raise ValueError(tool)Each entry in the in-memory call list records one stub invocation. A cache hit does not append to it. We count calls in the fixed crash-after-first-result example, and we inspect the log separately to identify steps available on recovery.
The crash injection raises after a selected completion is committed. In the duplicate-delivery example, the first claim expires before a second worker claims the task, and the first worker’s subsequent turn is rejected.
PythonIn [16]Expand
def run_task(
worker_id: str,
task: dict,
crash_after_step: int | None = None,
max_steps: int = 20,
) -> str:
task_id = task["id"]
plan = plan_for(task["kind"])
for _ in range(max_steps + 1):
if not renew_lease(worker_id, task):
return "lost_lease"
state = fold_events(read_events(task_id))
next_step = state["completed_step"]
if next_step >= len(plan):
transition = worker_commit(
worker_id, task, [], terminal="completed"
)
return "completed" if transition == "ok" else transition
if _ == max_steps:
break
step = plan[next_step]
call_id = f"s{next_step}"
transition = worker_commit(
worker_id,
task,
[
(
"tool_called",
{
"call_id": call_id,
"tool": step["tool"],
"input": step["input"],
"step": next_step,
},
)
],
)
if transition != "ok":
return transition
result = call_with_idempotency(
task_id,
next_step,
step["tool"],
step["input"],
lambda data: execute_tool(step["tool"], data),
)
transition = worker_commit(
worker_id,
task,
[
(
"tool_result",
{
"call_id": call_id,
"tool": step["tool"],
"key": result["key"],
"output": result["result"],
"cached": result["cached"],
},
),
(
"model_response",
{"step": next_step + 1, "text": f"did {step['tool']}"},
),
],
)
if transition != "ok":
return transition
if next_step == crash_after_step:
raise RuntimeError(f"simulated crash after step {crash_after_step}")
return "yield:max_steps"A few observations on the loop:
- The replay at the top of every iteration is what makes crash recovery automatic: after a crash, the next worker's first loop turn rebuilds
statefrom the log before doing anything else. We never have to reconstruct state manually. call_idis deterministic fromnext_step, so the fold can pair atool_calledwith itstool_resultunambiguously.- The idempotency key includes
next_step, so the same step and input yield the same key after restart. If the effect ran and theidemrow committed before the crash, the next attempt reads the recorded result. A crash after the effect and before the cache insert can leave onlytool_calledin the event log, so the next attempt can run the stub again. The reconciliation example below illustrates this gap. - The
crash_after_stepinjection raises after completion events are committed. The separate crash-window fixture below exercises the earlier interruption after the stub ran and before its result was recorded.
On a restart, the worker reconstructs completed steps from durable events. Its next transition also depends on the current lease generation, task deadline, and result cache. The ownership checks coordinate workers that can otherwise replay the same log independently.
We also need a small scheduler that can submit tasks, run one worker turn, and report state. Let's write that, then run a happy path.
PythonIn [17]Expand
def submit(
kind: str, input_dict: dict, deadline_seconds: float | None = 60.0
) -> str:
task_id = f"task_{uuid.uuid4().hex[:8]}"
now = time.time()
with tx() as con:
con.execute(
"""INSERT INTO tasks (id, kind, input, status, attempts, deadline, created_at)
VALUES (?, ?, ?, 'pending', 0, ?, ?)""",
(
task_id,
kind,
json.dumps(input_dict),
now + deadline_seconds
if deadline_seconds is not None
else None,
now,
),
)
return task_id
def status_of(task_id: str) -> dict:
con = DB
con.row_factory = sqlite3.Row
row = con.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone()
return dict(row) if row else {}Submission persists an intent and returns its ID. Completion still requires worker capacity and a usable deadline. A subsequent scheduler sweep can fail an expired unclaimed task without starting a tool.
Writing the accepted request before acknowledging it means a process restart need not lose the record. The fixture keeps its database open while it simulates the next worker reading an earlier worker’s committed state. It does not demonstrate recovery after loss of that database or process.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!