Skip to content
Projects
Reference implementation

agent-task-runtime

A crash-safe, lease-based task runtime for long-running agent jobs, as a dependency-free Python package on SQLite.

Status
Reference implementation. Single host, single SQLite file; simulated executors only, no model calls. No benchmarks.
Authorship
"Implemented with AI coding agents (Claude Code)," in the repository's own words: an independent reference implementation written from scratch, not extracted from any production system.
Stack
Python 3.11+ · SQLite (standard library) · pytest · ruff · uv
Demonstrates
Leases and fencing tokens · Transactional outbox · Checkpoint and resume · Retry with backoff and dead-lettering · Append-only audit log enforced by triggers
Verified
171 pytest tests pass, ruff check and format check are clean, and the scripted demo is deterministic across runs. Observed at commit bbad5e32851f52faa9039f64af7de4962185dd6a.
Commands run
uv sync
uv run pytest -q
uv run ruff check .
uv run ruff format --check .
uv run python -m agent_task_runtime demo
Repository
github.com/Donovanfitch-dev/agent-task-runtime

Engineering problem

Agent jobs are long, multi-step and unreliable in ordinary ways. A job that researches, drafts and reviews can take minutes, and in that time the worker can be killed, stall, lose its network, or just be slow enough that the system decides it died. Three failures follow from a naive pop, run and acknowledge queue:

  • The zombie worker.Worker A stalls, its lease expires, worker B takes over, and then A wakes up and finishes the task anyway, overwriting B's result.
  • The dual write.A task finishes, but the process dies before the downstream system is told.
  • Lost progress.A retried job starts again from the beginning and repeats every expensive step it had already done.

Representative solution

A small, readable implementation of the standard answers: time-limited leases, a monotonic fencing token checked on every write, per-step checkpoints, and a transactional outbox, tied together by an explicit state machine and an append-only event log. Everything that changes state lives in one module, store.py, and each mutating method is a single BEGIN IMMEDIATE transaction, so SQLite's single-writer lock is the serialization mechanism.

The repository states its guarantees and its non-guarantees separately. The guarantees hold for one SQLite file on a local filesystem with every process using the library. It does not offer exactly-once execution or exactly-once delivery, and it says so.

Architecture

A client enqueues tasks into the SQLite file. A worker loop claims a task under a lease, runs an executor that checkpoints and heartbeats through the store, and completes or fails it. A lease reaper re-queues expired leases, or dead-letters a task when its attempts run out. Terminal states write an outbox row in the same transaction, and a dispatcher delivers outbox rows to a sink at least once.

  • tasksCurrent state, priority, fencing token, release count, lease owner and deadline.
  • task_eventsAppend-only audit log. UPDATE and DELETE are blocked by database triggers.
  • checkpointsThe latest output per task and step.
  • outboxEvents awaiting delivery, with backoff state.
  • schema_migrationsWhich versioned migrations have run.
  • Processes using the library

    Many workers; one writer at a time

    • client or CLI
    • worker loop and executor
    • lease reaper
    • outbox dispatcher
  • One SQLite file

    Every state change is one BEGIN IMMEDIATE transaction

    Tables

    • tasks
    • task_events
    • checkpoints
    • outbox
    • schema_migrations

    task_events is append-only, enforced by triggers

  • Sinks

    Receive each outbox event at least once, keyed task_id:event_type

    • DedupSink
    • simulated flaky sinks

    the repository ships demonstration sinks only

What lives inside the store, what runs against it, and what sits outside it. Containment only; the protocol is described in the prose above.

Core components

  • TaskStore (store.py).Every state transition, one transaction each: enqueue, claim, heartbeat, checkpoint, complete, fail, release, cancel and reap.
  • State machine (models.py).The transition table is enforced on every write, and an illegal transition raises IllegalTransitionError.
  • Worker and TaskContext (worker.py).The worker loop, the one-method Executor protocol, cooperative graceful shutdown, and the context an executor uses to checkpoint and heartbeat.
  • RetryPolicy (retry.py).Exponential backoff with bounded jitter and a maximum attempt count, with an injectable clock and random number generator.
  • OutboxDispatcher and sinks (outbox.py, sinks.py).At-least-once delivery with a stable idempotency key per event, and a DedupSink that shows how a consumer absorbs duplicates.
  • Migrations (migrations.py).Versioned, run-once migrations that roll back on failure.
  • CLI and demo (cli.py, demo.py).enqueue, stats, inspect, work, dispatch, and the deterministic scenario recorded below.

Engineering decisions

  • SQLite.A reference implementation should run with a clone and nothing else, and SQLite provides real transactions, a real write lock and real durability in the standard library. That keeps the protocol, not the infrastructure, as the interesting part.
  • The fencing token is the claim counter.A lease alone is not safe, because a paused process cannot know its lease lapsed. Conditioning every write on the current token needs no extra column and is monotonic by construction.
  • At-least-once plus idempotent consumers.Exactly-once across a process boundary is not achievable in general. The outbox provides at-least-once delivery, and every event carries the key <task_id>:<event_type> so a consumer can deduplicate.
  • Heartbeats cover one step, not the whole job.Executors renew the lease between steps, so the lease only has to outlast the longest single step. The 30-second default is a placeholder, not a recommendation.
  • Lease expiry re-queues immediately; a reported failure waits for backoff.A crash is not the task's fault, so it should not cost the task its retry delay.

Tradeoffs

  • One writer, one host.SQLite's single-writer lock makes the protocol simple to reason about and limits the runtime to one machine. Many workers are supported, but they serialize on the write lock.
  • Lease duration.Too short and healthy but slow workers lose their tasks; too long and a crashed worker's task sits idle. The runtime leaves the number to the caller.
  • What would change for Postgres or multiple nodes.Claim becomes a SELECT using FOR UPDATE SKIP LOCKED, lease deadlines move to the database server's clock, the dispatcher needs partitioning or advisory locks, and workers need a background heartbeat thread. None of that is implemented.

Verified functionality

The repository's status table marks the following as implemented and tested. The test suite below exercises each of them, and the recorded demonstration shows the crash and takeover path end to end.

  • Atomic claim with priority then FIFO ordering, including concurrent claimers on separate connections
  • Leases, fencing tokens, heartbeat, and stale-write rejection that leaves the task, its log, its checkpoints and its outbox unchanged
  • The lease reaper, including dead-lettering when attempts are exhausted
  • Idempotent enqueue, including concurrent duplicates, and IdempotencyConflictError when a key is reused with different content
  • Checkpoints and resume after a crash
  • The transactional outbox, its dispatcher and backoff, and survival across a close and reopen of the database
  • Versioned migrations that run once, roll back on failure, and are safe under a race
  • The worker loop and graceful shutdown

Demonstration

The repository ships a scripted scenario that runs on a virtual clock with a seeded random number generator: no sleeping, no network, and the same output every time. A worker claims a task, checkpoints two steps and crashes; the lease expires; a second worker resumes from the checkpoints; the crashed worker wakes up and every write it attempts is rejected; and the outbox delivers the completion event through two outages and a lost acknowledgement.

The crash is simulated: it is an exception that bypasses the worker's error handling, not a killed process. The executors are simulations and call no model.

Crash, takeover, fencing and at-least-once delivery

Command: $ uv run python -m agent_task_runtime demo

agent-task-runtime demo: virtual clock, seeded RNG, no network, no sleeping
lease = 30s, each simulated agent step = 2s

--- 1. enqueue (idempotent) ---
[t=   0.0s] client    enqueue task-demo-1 priority=5 -> created=True
[t=   0.0s] client    enqueue same idempotency key -> created=False, same id: True

--- 2. worker-A claims, works, then crashes mid-task ---
[t=   0.0s] worker-A  claimed task-demo-1: attempt=1, fencing token=1, lease until t=30.0s
[t=   0.0s] worker-A  running step 'plan' ...
[t=   2.0s] worker-A  running step 'gather' ...
[t=   4.0s] worker-A  CRASH before step 'analyze' (process dies; lease not released)
[t=   4.0s] store     checkpoints on disk: ['plan', 'gather']; task state=leased

--- 3. lease expires; reaper reclaims ---
[t=  20.0s] reaper    scan: 0 expired leases (lease still valid until t=34.0s)
[t=  36.0s] reaper    lease expired -> task-demo-1 back to 'queued' (attempts used: 1/5)

--- 4. worker-B takes over and resumes from checkpoint ---
[t=  36.0s] worker-B  claimed task-demo-1: attempt=2, fencing token=2
[t=  36.0s] worker-B  resuming; checkpoints found: ['plan', 'gather']
[t=  36.0s] worker-B  running step 'analyze' ...
[t=  38.0s] worker-B  running step 'draft' ...
[t=  40.0s] worker-B  running step 'review' ...
[t=  42.0s] worker-B  completed task-demo-1; result.ran=['analyze', 'draft', 'review'], resumed=['plan', 'gather']
[t=  42.0s] store     terminal state AND outbox event were committed in one transaction

--- 5. zombie worker-A wakes up and tries to finish ---
[t=  46.0s] zombie-A  heartbeat(token=1) REJECTED: stale lease on task-demo-1: presented fencing token 1, current token is 2 and task state is succeeded
[t=  46.0s] zombie-A  checkpoint(token=1) REJECTED: stale lease on task-demo-1: presented fencing token 1, current token is 2 and task state is succeeded
[t=  46.0s] zombie-A  complete(token=1) REJECTED: stale lease on task-demo-1: presented fencing token 1, current token is 2 and task state is succeeded
[t=  46.0s] store     unchanged: state=succeeded, attempt=2, result.ran=['analyze', 'draft', 'review']

--- 6. process restart, then outbox delivery (at-least-once) ---
[t=  46.0s] process   closing the database and reopening the file (simulated restart)
[t=  46.0s] store     after restart: outbox pending=1, delivered=0
[t=  46.0s] dispatch  delivery of task.succeeded FAILED (SinkUnavailableError: downstream unavailable (simulated)); retry at t=46.8s
[t=  46.8s] dispatch  delivery of task.succeeded FAILED (SinkUnavailableError: downstream unavailable (simulated)); retry at t=48.7s
[t=  48.7s] sink      EFFECT applied for key=task-demo-1:task.succeeded
[t=  48.7s] dispatch  delivery of task.succeeded FAILED (AckLostError: sink applied the event but the acknowledgement was lost); retry at t=51.4s
[t=  51.4s] dispatch  delivered task.succeeded key=task-demo-1:task.succeeded (duplicate delivery ignored by the dedup sink)
[t=  51.4s] dispatch  outbox: 1 delivered, 0 pending; sink attempts=4, effects applied=1, duplicates ignored=1

--- 7. append-only audit log for the task ---
  #1  t=   0.0s  client           enqueued       - -> queued          attempt=0
  #2  t=   0.0s  worker-A         claimed        queued -> leased     attempt=1
  #3  t=  36.0s  reaper           lease_expired  leased -> queued     attempt=1
  #4  t=  36.0s  worker-B         claimed        queued -> leased     attempt=2
  #5  t=  42.0s  worker-B         succeeded      leased -> succeeded  attempt=2

invariants held: 1 terminal state, 1 effect applied, 1 duplicate absorbed, 0 zombie writes
Exit code 0. Recorded output, unedited.Worker A holds fencing token 1 and dies after two checkpoints. Worker B gets token 2 and runs only the three remaining steps. A's three late writes are all rejected and the stored result does not change. The outbox row survives a simulated restart, and the redelivery after a lost acknowledgement is absorbed by the deduplicating sink.

Reproduce it

git clone https://github.com/Donovanfitch-dev/agent-task-runtime.git && cd agent-task-runtime
git checkout bbad5e3
uv sync
uv run python -m agent_task_runtime demo

Failure modes and limitations

  • Not exactly-once execution.If a worker crashes after an external side effect but before complete, the next attempt repeats it. Fencing protects this store; it cannot reach into other systems unless the token is passed downstream.
  • A zombie keeps running until it touches the store.Fencing detects a stale owner at its next fenced write, not before.
  • Two dispatchers can deliver the same event.Nothing claims outbox rows, so a second dispatcher on the same database may double-send. The runtime is designed for one dispatcher.
  • Shared clock.Lease expiry compares wall-clock timestamps, so every process must share a clock, and a clock step can expire leases early or late.
  • Durability is not crash-tested at the process level.Tests use threads and close and reopen the database file. No test kills a process mid-transaction or simulates power loss.
  • No fairness or throughput claims.Ordering is priority then FIFO, sustained high-priority load can starve low-priority tasks, and there are no benchmarks.
  • Not tamper-evident.The audit log is append-only against ordinary statements, but anyone with write access to the file can drop the triggers, and there is no hash chain.

Testing and validation

On 2026-11-10, against commit bbad5e3: uv run pytest -q reported 171 passed on Python 3.11, and ruff's lint check and format check both exited cleanly over the whole repository (the exact commands are listed in the header above). The repository's GitHub Actions workflow concluded success on the same commit.

  • Concurrency.Exclusive claims and idempotent enqueue are tested with threads on separate connections in one process. There is no multi-process test.
  • Fencing.Every rejected stale call is checked by comparing the task, its audit log, its checkpoints and its outbox before and after.
  • Determinism.The demo runs on a virtual clock with a seeded random number generator. Two runs produced byte-identical output, identical to the output pasted in the README.
  • Not covered.The long-running work and dispatch loops with signal handling were run once during the build and have no automated test.

Source and documentation