Durable Job

AI agent sessions are inherently fragile. A cloud host gets recycled, an API times out, or a context window fills up halfway through an hour of work — and if the task only existed inside that session, both accountability and verified progress vanish the instant the process dies.

Durable Job separates the logical piece of work from the disposable agent runs that try to complete it. The hub stores the job under one permanent ID, tracks each worker run as a numbered Attempt, and persists structured Checkpoints so a replacement worker picks up verified progress instead of restarting from scratch — while locking out any old attempt that wakes up late.

Group Work structure
Also known as Durable Execution, Checkpoint and Resume
Core rule Only the job's current running attempt may save checkpoints or report results
Defines records Job, Attempt, Checkpoint

Why work must outlive its agent session

Whether an agent is digesting a hundred compliance documents, reconciling billing exports, or implementing a backend service, long-running work routinely outlasts a single session. When a task lives only inside a live session, a sudden exit leaves the requester's board stuck on "in progress" with nobody responsible — until a human notices days later and starts a fresh agent that repeats everything from zero.

Simply spawning a second worker is not safe either. Without an explicit handoff boundary, the replacement does not know which half of the work was actually verified, and if the stalled first worker later reconnects, it can overwrite the replacement's state with stale reports.

Durable Job solves both failure modes with three structural rules enforced by the hub:

  1. A Job outlives every session and always names one assignee. Its ID never changes; the moment an attempt ends without finishing, the hub atomically closes the attempt and returns assignee_id to the Lead agent.
  2. Each run is a numbered, fenced Attempt. Every worker assignment opens a new attempt (1, 2, 3...) and sets current_attempt_id. Every checkpoint or report must carry that attempt ID; any message from a closed attempt is rejected with not_the_current_attempt.
  3. Checkpoints separate verified progress from work in progress. Workers save external artifacts first, then write an immutable Checkpoint naming what is verified with evidence, what is still half-finished, and where the saved artifacts live.

Why separate verified steps from in-progress notes inside a checkpoint? Because the costliest resume bug is a replacement worker assuming half-finished work is done. Listing verified steps alongside concrete evidence (and keeping unfinished work explicitly marked in_progress) lets Attempt 2 confirm the saved baseline quickly and build forward without silent corruption.

Session-bound task Worker 1 starts in one session Progress lives only in session state Host recycles or context fills Session exits silently; no one owns it Board stays stuck "in progress" Human notices days later and restarts Replacement starts from zero Paid twice; zombie worker can collide Durable Job Hub opens Job + Attempt 1 Worker 1 saves external checkpoints Attempt 1 stops unexpectedly Hub marks lost & returns job to Lead Attempt 2 resumes from checkpoint Late reports from Attempt 1 fenced out Job finishes without human chase Verified work kept; zero duplicate effort
A session-bound task loses ownership and progress the moment its process dies. Durable Job keeps the work in the hub, returns ownership to the lead on loss, resumes Attempt 2 from the last checkpoint, and rejects late reports from Attempt 1.

Architecture and participants

The hub maintains a strict durability chain: one Request owns one or more Job records, each job records every Attempt made on it, and each attempt appends immutable Checkpoint snapshots pointing to artifacts saved outside any agent container. Agent sessions themselves are treated as disposable compute.

Lead agent Assigns & reclaims jobs Hub Fences current attempt External storage Branches, files, rows Hub durable records (outlive every agent session) Job Permanent ID & assignee Attempt (1, 2, ...) At most 1 running Checkpoint Verified vs in-progress Worker 1 (Attempt 1 — lost) Disposable; fenced on reconnect Worker 2 (Attempt 2 — running) Resumes from cp; active writer
Durable state lives exclusively in the hub's Request → Job → Attempt → Checkpoint chain. Ephemeral worker sessions come and go; only the single running attempt named by current_attempt_id may write back.
Lead agent
Creates and assigns jobs, automatically becomes assignee_id whenever a job has no live worker, reassigns lost jobs to replacement workers, and marks jobs done.
Hub
Persists Job, Attempt, and Checkpoint atomically; enforces the single-current-attempt fence and reverts ownership on failure.
Workers (Worker 1, Worker 2)
Each executes one numbered attempt in an ephemeral session, persists artifacts to durable storage, stamps checkpoints with its attempt_id, and reports completion to the hub.
Job, Attempt & Checkpoint
Three separate records: the permanent piece of work, one worker's bounded try at it, and a verified progress snapshot pointing to external artifacts.

Execution flow

Toggle between the normal path — where Worker 1 saves two checkpoints and completes in one attempt — and the crash recovery path — where Worker 1's machine recycles, ownership snaps back to the lead, Worker 2 resumes from Checkpoint 2, and a revived Attempt 1 is fenced out.

Lead agent Hub Worker 1 Job record 1. Create & assign job to Worker 1 2. Store Job + open Attempt 1 3. Start Worker 1 with Attempt 1 ID 4. Save Checkpoint 1 (as Attempt 1) 5. Save Checkpoint 2 (as Attempt 1) 6. Report result (as Attempt 1) 7. Verify current attempt; forward 8. Mark job done (close Attempt 1) 9. Persist done + Attempt 1 finished

The hub opens Attempt 1 when the lead assigns the job. Worker 1 saves external artifacts and two checkpoints stamped with Attempt 1, reports completion, and the lead closes the job and attempt in one atomic transition.

Concrete examples

Durable Job protects any work whose output can be saved outside the agent session — from multi-hour document audits to feature branches in a repository.

Example 1 — 120-document vendor privacy digest

No code or unit tests
Job
Extract data-retention periods and sub-processor clauses from 120 vendor privacy policies into one structured compliance spreadsheet.
Checkpoints & loss
Worker 1 uploads the spreadsheet to shared storage after every 35 policies and saves Checkpoint 2: verified = rows 1–75 cross-checked against source clauses; in_progress = policy 76 half-reviewed; artifacts = privacy-digest-v2.csv. At policy 80, Worker 1 fills its context window and exits.
Recovery
The hub marks Attempt 1 lost and returns the job to the lead. Attempt 2 starts Worker 2 from Checkpoint 2 — spot-checking row 75 and finishing policies 76–120 without paying to re-read the first 75 documents.

Example 2 — Webhook delivery retries and logging

Everyday engineering
Job
Add exponential backoff retries and delivery logging whenever a customer's webhook endpoint fails to respond.
Checkpoints & loss
Worker 1 pushes commits to fix/webhook-retries and saves Checkpoint 2: verified = retry schedule verified at commit 3f2c9a1; in_progress = delivery log half-written. Five minutes later, its container host is recycled silently.
Recovery
The hub closes Attempt 1 as lost, hands ownership back to the lead, and opens Attempt 2 for Worker 2 pointing at Checkpoint 2. When Worker 1's old container briefly reconnects and tries to save as Attempt 1, the hub rejects it with not_the_current_attempt. Worker 2 confirms the saved baseline, finishes the delivery log, and closes the job cleanly.

What this pattern is NOT — 20-second lookup or live browser session

Negative example
Request
Run a 20-second read-only lookup, or hold a live interactive browser login whose in-memory cookies cannot be exported to another machine.
Why skip it
For a tiny cheap task, restarting from zero is faster than writing checkpoints (keep Job and Attempt, omit checkpoints). And when progress cannot be stored outside the session, a checkpoint cannot actually be resumed by Attempt 2 — it only creates false reassurance.

When to use and when to skip

Use Durable Job when

  • Workers run in containers or model sessions that can crash, recycle, time out, or hit context limits without warning.
  • Work takes long enough — or costs enough tokens — that repeating finished progress from zero hurts.
  • Intermediate output can be persisted outside the session (branches, files, spreadsheets, or database rows).
  • Other records (questions, waits, reviews, leases) need a stable job ID that survives worker replacement.

Skip parts of it when

  • A task is so brief and inexpensive that retrying from scratch beats checkpoint overhead (drop checkpoints, keep Job/Attempt).
  • One human and one agent finish the work inside a single live chat thread.
  • Intermediate state is trapped inside a live session and cannot be externalized for a replacement worker.

Data model and hub invariants

Durable Job defines three core tables — jobs, attempts, and checkpoints — pointing to requests and parties (Orchestrator-Workers) and request_specs (Request Spec).

Request PK id Request spec PK id Party PK id 1 n 1 n 1 n Job PK id FK request_id FK request_spec_id title instructions? FK assignee_id state FK current_attempt_id? assigned_at last_heard_at leftovers_listed_at? finished_at? Attempt PK id FK job_id number FK worker_id state FK from_checkpoint_id? session_ref? started_at ended_at? end_reason? Checkpoint PK id FK attempt_id FK job_id verified in_progress? artifacts notes? saved_at 1 n 1? 1 1 n 1? n 1 job_id (direct lookup for latest checkpoint) n
A Job holds one permanent ID across many sequential Attempt rows and points to at most one running attempt. Each Checkpoint tags both its attempt and its job so the latest checkpoint is directly queryable.

Table: jobs

Column Postgres type Nullability Notes
id uuid NOT NULL, PK Permanent job ID that never changes across attempts.
request_id uuid NOT NULL, FK References requests(id).
request_spec_id uuid NOT NULL, FK References request_specs(id); pinned spec version.
title text NOT NULL Short name of this piece of work.
instructions text NULLABLE Lead agent's job-specific guidance when the spec alone isn't enough.
assignee_id uuid NOT NULL, FK References parties(id); worker while active, lead when unassigned or lost.
state text NOT NULL CHECK (state IN ('unassigned', 'working', 'waiting', 'lost', 'done', 'canceled')).
current_attempt_id uuid NULLABLE, FK References attempts(id); null when unassigned, lost, or canceled.
assigned_at timestamptz NOT NULL When the current assignee took ownership.
last_heard_at timestamptz NOT NULL Last hub contact from the current assignee.
leftovers_listed_at timestamptz NULLABLE Timestamp when close-out leftovers were enumerated (Close-Out Triage).
finished_at timestamptz NULLABLE Set atomically when state becomes done.

Table: attempts

Column Postgres type Nullability Notes
id uuid NOT NULL, PK Fencing ID included by the worker on every checkpoint and report.
job_id uuid NOT NULL, FK References jobs(id).
number integer NOT NULL Sequential attempt number starting at 1; UNIQUE (job_id, number).
worker_id uuid NOT NULL, FK References parties(id) executing this attempt.
state text NOT NULL CHECK (state IN ('running', 'finished', 'handed_back', 'lost', 'replaced')).
from_checkpoint_id uuid NULLABLE, FK References checkpoints(id) that this attempt resumed from.
session_ref text NULLABLE Runtime container or session identifier so the hub can terminate stale runs.
started_at timestamptz NOT NULL When the hub opened this attempt.
ended_at timestamptz NULLABLE Null while running; set atomically on any terminal attempt state.
end_reason text NULLABLE Human-readable explanation (e.g. "Container host recycled").

Table: checkpoints

Column Postgres type Nullability Notes
id uuid NOT NULL, PK Unique checkpoint identifier.
attempt_id uuid NOT NULL, FK References attempts(id) that saved this checkpoint.
job_id uuid NOT NULL, FK Denormalized jobs(id) so latest checkpoint queries stay O(1).
verified jsonb NOT NULL Array of {step, evidence} entries already confirmed.
in_progress text NULLABLE Unfinished step in flight — must never be treated as verified by the next worker.
artifacts jsonb NOT NULL Array of {kind, ref} external locations (branches, commits, files).
notes text NULLABLE Dead ends tried or pitfalls for the next worker to avoid.
saved_at timestamptz NOT NULL Hub timestamp when saved; newest saved_at wins.

Eight hub invariants

  1. 01
    Every job belongs to one request and keeps its ID for life Database constraint

    jobs.request_id is NOT NULL referencing requests(id), giving questions, waits, and leases a permanent anchor across worker turnover.

  2. 02
    Every job always names an assignee matching its state Hub guard

    assignee_id is the current attempt's worker while working or waiting, and immediately reverts to the request's lead agent while unassigned or lost.

  3. 03
    At most one running attempt per job, numbered from 1 Database constraint

    Enforced by a partial unique index UNIQUE (job_id) WHERE state = 'running' and UNIQUE (job_id, number) so two workers never run concurrently on the same job.

  4. 04
    Ended attempts carry ended_at and never run again Database constraint

    CHECK ((state = 'running') = (ended_at IS NULL)) guarantees clean lifecycle timestamps, and closed attempts can never transition back to running.

  5. 05
    Opening or closing an attempt updates job and attempt atomically Hub guard

    assign only accepts jobs in unassigned or lost state (else job_not_assignable), writing both the job and the new attempt in one transaction.

  6. 06
    Only the current running attempt may save checkpoints or report Hub guard

    Every write verifies attempt.state == 'running' and job.current_attempt_id == attempt.id, rejecting revived or replaced workers with not_the_current_attempt.

  7. 07
    Checkpoints are immutable and match their attempt's job Database constraint

    A composite foreign key (job_id, attempt_id) referencing attempts(job_id, id) ensures every checkpoint belongs to the right job, and saved rows are never edited in place.

  8. 08
    Only the lead marks a job done; terminal jobs never change Hub guard

    finish enforces only_lead_may_finish_job and job_already_terminal, setting finished_at and closing the attempt atomically.

Reference implementation

The same atomic job, attempt, and checkpoint state machine in TypeScript, Python, and Elixir — ensuring crashed sessions never orphan work and zombie attempts never corrupt state.

-- Hub guards for Durable Job (atomic job/attempt transitions + attempt fence)
import Std.Data.HashMap
open Std (HashMap)

inductive JobState where
  | unassigned | working | waiting | lost | done | canceled
  deriving Repr, BEq

inductive AttemptEndReason where
  | lost | handedBack | replaced
  deriving Repr, BEq

inductive AttemptState where
  | running | finished
  | ended (how : AttemptEndReason)  -- closed as lost, handed back or replaced
  deriving Repr, BEq

structure Job where
  id : String
  leadId : String
  assigneeId : String
  state : JobState := .unassigned
  currentAttemptId : Option String := none
  finishedAt : Option String := none
  deriving Repr

structure Attempt where
  id : String
  jobId : String
  number : Nat
  workerId : String
  state : AttemptState := .running
  fromCheckpointId : Option String := none
  endedAt : Option String := none
  endReason : Option String := none
  deriving Repr

structure VerifiedStep where
  step : String
  evidence : String
  deriving Repr

structure Artifact where
  kind : String
  ref : String
  deriving Repr

structure Checkpoint where
  id : String
  jobId : String
  attemptId : String
  verified : List VerifiedStep := []
  inProgress : Option String := none
  artifacts : List Artifact := []
  savedAt : String
  deriving Repr

inductive HubError where
  | unknownJob | jobNotAssignable | notTheCurrentAttempt
  | jobAlreadyTerminal | onlyLeadMayFinishJob
  deriving Repr, BEq

-- The hub is plain data; every guard returns a new hub or an error.
structure DurableJobHub where
  jobs : HashMap String Job := {}
  attempts : HashMap String Attempt := {}
  checkpoints : List Checkpoint := []  -- newest first

namespace DurableJobHub

def latestCheckpoint (hub : DurableJobHub) (jobId : String) : Option Checkpoint :=
  hub.checkpoints.find? (·.jobId == jobId)  -- `·` stands for each checkpoint

-- The attempt fence: only the running attempt the job points at may act.
def requireCurrent (hub : DurableJobHub) (attemptId : String) :
    Except HubError (Job × Attempt) := do
  let some attempt := hub.attempts.get? attemptId | throw .notTheCurrentAttempt
  let some job := hub.jobs.get? attempt.jobId | throw .notTheCurrentAttempt
  unless attempt.state == .running && job.currentAttemptId == some attemptId do
    throw .notTheCurrentAttempt
  pure (job, attempt)

-- Job and attempt are written together, so the two can never disagree.
def putPair (hub : DurableJobHub) (job : Job) (attempt : Attempt) : DurableJobHub :=
  { hub with jobs := hub.jobs.insert job.id job,
             attempts := hub.attempts.insert attempt.id attempt }

def assign (hub : DurableJobHub) (jobId workerId attemptId : String) :
    Except HubError (Attempt × DurableJobHub) := do
  let some job := hub.jobs.get? jobId | throw .unknownJob
  unless job.state == .unassigned || job.state == .lost do throw .jobNotAssignable

  let earlier := hub.attempts.values.filter (·.jobId == jobId) |>.map (·.number)
  let attempt : Attempt := {
    id := attemptId, jobId, workerId
    number := earlier.foldl max 0 + 1
    fromCheckpointId := (hub.latestCheckpoint jobId).map (·.id) }
  let job := { job with assigneeId := workerId, state := .working,
                        currentAttemptId := some attemptId }
  pure (attempt, hub.putPair job attempt)

def saveCheckpoint (hub : DurableJobHub) (attemptId : String) (cp : Checkpoint) :
    Except HubError (Checkpoint × DurableJobHub) := do
  let (job, _) ← hub.requireCurrent attemptId
  let saved := { cp with jobId := job.id, attemptId }
  pure (saved, { hub with checkpoints := saved :: hub.checkpoints })

def closeAttempt (hub : DurableJobHub) (attemptId : String) (how : AttemptEndReason)
    (reason now : String) : Except HubError (Job × DurableJobHub) := do
  let (job, attempt) ← hub.requireCurrent attemptId
  let closed := { attempt with state := .ended how, endedAt := some now,
                               endReason := some reason }
  let nextState := if how == .lost then JobState.lost else .unassigned
  let job := { job with assigneeId := job.leadId, state := nextState, currentAttemptId := none }
  pure (job, hub.putPair job closed)

def finish (hub : DurableJobHub) (attemptId actorId now : String) :
    Except HubError (Job × DurableJobHub) := do
  let some attempt := hub.attempts.get? attemptId | throw .notTheCurrentAttempt
  let some job := hub.jobs.get? attempt.jobId | throw .notTheCurrentAttempt
  if job.state == .done || job.state == .canceled then throw .jobAlreadyTerminal
  unless attempt.state == .running && job.currentAttemptId == some attemptId do
    throw .notTheCurrentAttempt
  unless actorId == job.leadId do throw .onlyLeadMayFinishJob

  let doneAttempt := { attempt with state := .finished, endedAt := some now }
  let doneJob := { job with state := .done, finishedAt := some now }
  pure (doneJob, hub.putPair doneJob doneAttempt)

end DurableJobHub

-- Invariant: an attempt the hub has never seen can't save a checkpoint.
theorem saveCheckpoint_unknown (id : String) (cp : Checkpoint) :
    ({} : DurableJobHub).saveCheckpoint id cp = throw .notTheCurrentAttempt := by
  simp [DurableJobHub.saveCheckpoint, DurableJobHub.requireCurrent]; rfl

Crash, resume, and zombie-fencing trace

Walking Example 2 (webhook delivery retries and logging) through these guards shows ownership reverting to the lead, Attempt 2 resuming from Checkpoint 2, and Worker 1's late reconnect blocked with not_the_current_attempt:

Execution trace: Example 2 (webhook delivery retries and logging)
1. hub.assign(job_webhook_retries, worker_1, attempt_1)
   hub.saveCheckpoint(attempt_1, { id: cp_2, verified: [{ step: "retry schedule", evidence: "3f2c9a1" }],
     inProgress: "delivery log half-written", artifacts: [{ kind: "branch", ref: "fix/webhook-retries" }], savedAt: "10:45Z" })
   -> ok (current_attempt_id = attempt_1; latest checkpoint = cp_2)

2. // Worker 1's host recycles silently at 10:50Z; heartbeat detects loss at 10:55Z
   hub.closeAttempt(attempt_1, "lost", "Container host recycled", "10:55Z")
   -> ok (job.state = "lost"; job.assignee_id = lead_1; current_attempt_id = null)

3. hub.assign(job_webhook_retries, worker_2, attempt_2)
   -> ok (attempt_2.number = 2; from_checkpoint_id = cp_2; current_attempt_id = attempt_2)

4. // Worker 1 reconnects briefly and tries to write as attempt_1
   hub.saveCheckpoint(attempt_1, { id: cp_stale, verified: [], inProgress: "retry", artifacts: [], savedAt: "11:05Z" })
   -> error: not_the_current_attempt (attempt_1 is closed; state untouched)

5. // Worker 2 confirms commit 3f2c9a1, finishes delivery log, reports as attempt_2
   hub.finish(attempt_2, lead_1, "11:40Z")
   -> ok (job.state = "done"; attempt_2.state = "finished"; finished_at = "11:40Z")

Tradeoffs and practical guidance

Durable Job trades modest checkpointing discipline for resilience against every kind of agent interruption. Keep three honest costs in view:

  • Checkpoint token and latency tax: summarizing verified state and writing checkpoints takes time and tokens even on runs that finish cleanly on Attempt 1.
  • Self-reported verification risk: a checkpoint is still a worker's assertion. If Attempt 1 mislabels half-finished work as verified, Attempt 2 can build on a faulty foundation unless evidence is attached and spot-checked.
  • Not a failure detector by itself: Durable Job preserves state once an attempt is closed, but relies on Progress Heartbeat to notice silent stalls and Context Handoff to brief the replacement worker.

Practical implementation notes

  • Never use a session ID as the job ID: give every job its own UUID so questions, waits, reviews, and leases stay valid when workers swap out.
  • Externalize artifacts before saving the checkpoint: push the branch, upload the file, or write the row first — a checkpoint pointing to a dead container's local disk is useless.
  • Require evidence on every verified step: pair each verified entry with a commit hash, artifact link, or check output so Attempt 2 knows what was actually proven.
  • Terminate the old session as well as fencing it: the hub fence protects hub records, but killing the stale container and revoking its credentials stops it from pushing stray commits to external systems.
  • Cap maximum attempts: if a job repeatedly hits context limits across multiple attempts, stop reassigning blindly — escalate to the lead to split the job.

Known uses and related patterns

  • Temporal: provides durable execution by replaying deterministic workflow code and carrying activity progress inside heartbeats; Durable Job adapts the idea for non-deterministic agents via human- and agent-readable checkpoints pointing to external artifacts.
  • Kubernetes Jobs: keeps the logical Job object alive while spawning fresh Pods on failure; Durable Job adds explicit verified-vs-in-progress checkpoints so replacement workers do not redo completed steps.
  • LangGraph Checkpointers: persists graph state after each step to support resuming agent runs; Durable Job extends checkpoints with explicit external artifact references and strict attempt fencing.
  • Volgenic: keeps work items alive across agent launches and container restarts, fencing stale session tokens whenever a newer launch takes over.
  • Microsoft Azure Scheduler Agent Supervisor: stores step state in a durable supervisor and allows only the active attempt to mutate it; Durable Job layers readable checkpoints onto that coordination spine.

Related patterns

  • Progress Heartbeat — most easily confused with Durable Job; Durable Job stores the durable work and attempts, while Progress Heartbeat detects silent workers and triggers attempt closure.
  • Orchestrator-Workers — supplies the lead agent that receives ownership whenever a job loses its worker.
  • Request Spec — defines the immutable spec versions pinned by jobs.request_spec_id.
  • Context Handoff — packages the job's latest checkpoint together with facts and policies into Attempt 2's takeover briefing.
  • Resource Lease — prevents a replaced attempt or parallel job from modifying a shared file or branch concurrently.
  • Resumable Wait & Change Propagation — drive the waiting and canceled job states.
  • Evidence-Backed Completion, Close-Out Triage & Tracked Answer — enforce the close-out gates required before marking a job done.