Durable and Asynchronous Agent Work › Building a durable task runner

Michael BrenndoerferDecember 1, 20267 min read
Language AI HandbookAll chapters
Part 49 of 67Long-Horizon Agents and Interoperability
Chapter 376Durable and Asynchronous Agent Work › Building a durable task runner
Reading section 5 of 15 · Building a durable task runner · 7 minSection 5 of 15 · 7 min

Section 5 of 15 · 7 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The notebook keeps one open in-memory SQLite connection and simulates worker crashes and lease expiry as serial turns. This exercises transactions and stale-generation rejection with the database still running. Exiting the notebook discards the database; production restart recovery needs a persistent store independent of the worker process.

SQLite supplies real transactions, an ordered event log, and keyed lookup without a local file. A production store would need equivalent atomic ownership and transition checks under its own concurrency model.

The setup cell uses only Python standard-library modules.

PythonIn [8]
CollapseExpand
import hashlib
import json
import os
import random
import sqlite3
import threading
import time
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable

DEMO_DB_URI = ":memory:"

The schema

We need four things: tasks, events, leases (folded into tasks here for brevity), and an idempotency table. We'll keep everything in one open SQLite connection and use text JSON for events to keep the code legible.

PythonIn [9]
CollapseExpand
SCHEMA = """
CREATE TABLE tasks (
  id TEXT PRIMARY KEY,
  kind TEXT NOT NULL,
  input TEXT NOT NULL,
  status TEXT NOT NULL,            -- pending | running | completed | failed
  lease_worker TEXT,
  lease_until REAL,
  lease_epoch INTEGER NOT NULL DEFAULT 0,
  attempts INTEGER NOT NULL DEFAULT 0,
  deadline REAL,
  created_at REAL NOT NULL
);
CREATE TABLE events (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  task_id TEXT NOT NULL,
  seq INTEGER NOT NULL,            -- per-task monotonic sequence
  kind TEXT NOT NULL,
  payload TEXT NOT NULL,
  UNIQUE(task_id, seq)
);
CREATE TABLE idem (
  key TEXT PRIMARY KEY,
  result TEXT NOT NULL,
  created_at REAL NOT NULL
);
"""


def init_db(location=DEMO_DB_URI):
    connection = sqlite3.connect(location, isolation_level=None)
    connection.executescript(SCHEMA)
    return connection


DB = init_db()

The event sequence constraint guards duplicate positions. Worker ownership is a separate rule. The worker checks identity, generation, deadline and live lease inside the transaction that writes events or a terminal state.

The tasks table stores current state, lease holder, generation, expiry, and the attempt count. Events are inserted at a task-local sequence position. The result cache maps an effect key to its recorded result. Its presence is evidence of a local record; the upstream service controls the actual effect.

The event log helpers

We write a small set of helpers: append an event, read events since a given sequence, and fold the log into state. Folding is the "replay" that reconstructs what the agent believed at any point.

PythonIn [10]
CollapseExpand
@contextmanager
def tx():
    DB.execute("BEGIN IMMEDIATE")
    try:
        yield DB
        DB.execute("COMMIT")
    except BaseException:
        DB.execute("ROLLBACK")
        raise


def append_in_transaction(con, task_id, kind, payload):
    (seq,) = con.execute(
        "SELECT COALESCE(MAX(seq), 0) + 1 FROM events WHERE task_id = ?",
        (task_id,),
    ).fetchone()
    con.execute(
        "INSERT INTO events (task_id, seq, kind, payload) VALUES (?, ?, ?, ?)",
        (task_id, seq, kind, json.dumps(payload)),
    )


def apply_terminal(con, task_id, status, reason=None):
    payload = {"reason": reason} if reason is not None else {}
    append_in_transaction(con, task_id, f"task_{status}", payload)
    con.execute(
        """UPDATE tasks SET status=?, lease_worker=NULL, lease_until=NULL WHERE id=?""",
        (status, task_id),
    )


def worker_commit(worker_id, task, entries, *, terminal=None):
    task_id = task["id"]
    with tx() as con:
        now = time.time()
        owned = con.execute(
            """SELECT deadline FROM tasks
               WHERE id=? AND status='running' AND lease_worker=?
                 AND lease_epoch=? AND lease_until>?""",
            (task_id, worker_id, task["lease_epoch"], now),
        ).fetchone()
        if owned is None:
            return "lost_lease"
        (deadline,) = owned
        if deadline is not None and deadline <= now:
            apply_terminal(con, task_id, "failed", "deadline_exceeded")
            return "failed:deadline"
        for kind, payload in entries:
            append_in_transaction(con, task_id, kind, payload)
        if terminal is not None:
            apply_terminal(con, task_id, terminal)
    return "ok"


def read_events(task_id: str, after_seq: int = 0):
    with DB as con:
        rows = con.execute(
            "SELECT seq, kind, payload FROM events WHERE task_id = ? AND seq > ? ORDER BY seq",
            (task_id, after_seq),
        ).fetchall()
    return [{"seq": s, "kind": k, "payload": json.loads(p)} for s, k, p in rows]

BEGIN IMMEDIATE acquires the write lock at transaction start rather than deferring it, so the MAX(seq)+1 read and the INSERT are atomic: no two workers can pick the same seq.

BEGIN IMMEDIATE serializes writers before they perform the sequence read and insertion. The same write transaction validates the current task generation and lease before an event append. Sequence uniqueness detects collisions but does not authenticate the worker.

The fold: reconstructing agent state

The fold is one function per log kind. The reconstructed state is the minimum the agent needs to continue: the message list from prior tool calls, plus the number of the last completed step. If a model_response event is present for step i, we don't re-ask the model.

PythonIn [11]
CollapseExpand
def fold_events(events):
    state = {"messages": [], "completed_step": 0, "last_call": {}}
    for e in events:
        kind, p = e["kind"], e["payload"]
        if kind == "tool_called":
            state["last_call"][p["call_id"]] = {
                "tool": p["tool"],
                "input": p["input"],
            }
        elif kind == "tool_result":
            cid = p["call_id"]
            call = state["last_call"].pop(cid, None)
            state["messages"].append(
                {
                    "role": "tool",
                    "name": call["tool"] if call else p.get("tool"),
                    "content": p["output"],
                }
            )
        elif kind == "model_response":
            state["messages"].append(
                {"role": "assistant", "content": p["text"]}
            )
            state["completed_step"] = max(state["completed_step"], p["step"])
        elif kind == "task_completed":
            state["status"] = "completed"
    return state

The fold marks the task as completed when it sees task_completed. The runner reads failure status from the tasks table rather than folding task_failed into state. At replay, the last model_response marker tells it which completed steps to skip.

The fold rebuilds its task state from the same ordered events without a clock or external calls. It reconstructs recorded progress; an unrecorded outcome remains unknown.

Idempotent side effects

The result cache illustrates a logical effect key. The toy stubs run outside the local transaction, so there is a gap between the effect and the cached result. A cache hit avoids another stub invocation. The cache is not a remote idempotency guarantee.

PythonIn [12]
CollapseExpand
def logical_key(task_id, step, tool, tool_input):
    description = {"t": task_id, "s": step, "tool": tool, "i": tool_input}
    return hashlib.sha256(
        json.dumps(description, sort_keys=True).encode()
    ).hexdigest()


def call_with_idempotency(
    task_id: str,
    step: int,
    tool: str,
    tool_input: dict,
    fn: Callable[[dict], Any],
) -> Any:
    key = logical_key(task_id, step, tool, tool_input)
    with DB as con:
        row = con.execute(
            "SELECT result FROM idem WHERE key = ?", (key,)
        ).fetchone()
    if row is not None:
        return {"key": key, "cached": True, "result": json.loads(row[0])}

    # The stub effect happens outside the SQLite transaction. On a crash or a
    # duplicate cache miss the effect can happen again. A real upstream key
    # contract, when available, belongs inside this fn boundary.
    result = fn(tool_input)
    with tx() as con:
        con.execute(
            "INSERT OR IGNORE INTO idem (key, result, created_at) VALUES (?, ?, ?)",
            (key, json.dumps(result), time.time()),
        )
        (canonical,) = con.execute(
            "SELECT result FROM idem WHERE key = ?", (key,)
        ).fetchone()
    return {"key": key, "cached": False, "result": json.loads(canonical)}

A restart before the cache insert can repeat an operation, as can two concurrent cache misses. A winning result row is returned to every caller that reaches the post-call transaction, but it cannot undo another execution. The toy retains this gap to show why an upstream key contract matters.

With the same serialization options, sort_keys=True removes differences in dictionary key order. It does not make different numeric representations or serializers yield identical bytes. Specify how callers encode the fields when they must compute the same logical key.

Now let's wire those together. The folding at the end gives us a reconstructed state and the last completed step. When the worker loop below runs a step, it appends a tool_called event, calls the tool via call_with_idempotency, then appends tool_result and model_response events. For the demo, the tool is a stub that records each real execution in the EXECUTED list so we can watch it run, and that list is printed by the output-only demo blocks rather than from inside the tool.

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!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy