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.
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:
-
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_idto theLead agent. -
Each run is a numbered, fenced Attempt. Every worker assignment opens a
new attempt (
1, 2, 3...) and setscurrent_attempt_id. Every checkpoint or report must carry that attempt ID; any message from a closed attempt is rejected withnot_the_current_attempt. -
Checkpoints separate verified progress from work in progress. Workers
save external artifacts first, then write an immutable
Checkpointnaming 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.
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.
current_attempt_id may write back.
assignee_id
whenever a job has no live worker, reassigns lost jobs to replacement workers, and
marks jobs done.
Job, Attempt,
and Checkpoint atomically; enforces the single-current-attempt
fence and reverts ownership on failure.
attempt_id,
and reports completion to the hub.
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.
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.
Same steps 1–5 as normal flow; begins right after Worker 1 saves Checkpoint 2.
When Worker 1 stops, the hub atomically closes Attempt 1 as lost
and returns the job to the lead. The lead starts Attempt 2 for Worker 2 from Checkpoint 2;
when Worker 1 later reconnects and reports as Attempt 1, the hub rejects it with
not_the_current_attempt.
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
lostand 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-retriesand saves Checkpoint 2:verified= retry schedule verified at commit3f2c9a1;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 withnot_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).
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
-
01Every job belongs to one request and keeps its ID for life Database constraint
jobs.request_idisNOT NULLreferencingrequests(id), giving questions, waits, and leases a permanent anchor across worker turnover. -
02Every job always names an assignee matching its state Hub guard
assignee_idis the current attempt's worker whileworkingorwaiting, and immediately reverts to the request's lead agent whileunassignedorlost. -
03At most one running attempt per job, numbered from 1 Database constraint
Enforced by a partial unique index
UNIQUE (job_id) WHERE state = 'running'andUNIQUE (job_id, number)so two workers never run concurrently on the same job. -
04Ended 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 torunning. -
05Opening or closing an attempt updates job and attempt atomically Hub guard
assignonly accepts jobs inunassignedorloststate (elsejob_not_assignable), writing both the job and the new attempt in one transaction. -
06Only the current running attempt may save checkpoints or report Hub guard
Every write verifies
attempt.state == 'running'andjob.current_attempt_id == attempt.id, rejecting revived or replaced workers withnot_the_current_attempt. -
07Checkpoints are immutable and match their attempt's job Database constraint
A composite foreign key
(job_id, attempt_id)referencingattempts(job_id, id)ensures every checkpoint belongs to the right job, and saved rows are never edited in place. -
08Only the lead marks a job done; terminal jobs never change Hub guard
finishenforcesonly_lead_may_finish_jobandjob_already_terminal, settingfinished_atand 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
// Hub guards for Durable Job (atomic job/attempt transitions + attempt fence)
type JobState = "unassigned" | "working" | "waiting" | "lost" | "done" | "canceled";
type AttemptEndReason = "lost" | "handed_back" | "replaced";
interface Job {
id: string;
leadId: string;
assigneeId: string;
state: JobState;
currentAttemptId: string | null;
finishedAt: string | null;
}
interface Attempt {
id: string;
jobId: string;
number: number;
workerId: string;
state: "running" | "finished" | AttemptEndReason;
fromCheckpointId: string | null;
endedAt: string | null;
endReason: string | null;
}
interface Checkpoint {
id: string;
jobId: string;
attemptId: string;
verified: Array<{ step: string; evidence: string }>;
inProgress: string | null;
artifacts: Array<{ kind: string; ref: string }>;
savedAt: string;
}
class DurableJobHub {
private jobs = new Map<string, Job>();
private attempts = new Map<string, Attempt>();
private checkpoints: Checkpoint[] = [];
assign(jobId: string, workerId: string, attemptId: string): Attempt {
const job = this.jobs.get(jobId);
if (!job) throw new Error("unknown_job");
if (job.state !== "unassigned" && job.state !== "lost") {
throw new Error("job_not_assignable");
}
const prevNums = [...this.attempts.values()]
.filter((a) => a.jobId === jobId)
.map((a) => a.number);
const latest = this.latestCheckpoint(jobId);
const attempt: Attempt = {
id: attemptId,
jobId,
number: prevNums.length ? Math.max(...prevNums) + 1 : 1,
workerId,
state: "running",
fromCheckpointId: latest ? latest.id : null,
endedAt: null,
endReason: null
};
this.attempts.set(attemptId, attempt);
job.assigneeId = workerId;
job.state = "working";
job.currentAttemptId = attemptId;
return attempt;
}
saveCheckpoint(attemptId: string, cp: Omit<Checkpoint, "jobId" | "attemptId">): Checkpoint {
const { job } = this.requireCurrent(attemptId);
const saved: Checkpoint = { ...cp, jobId: job.id, attemptId };
this.checkpoints.push(saved);
return saved;
}
closeAttempt(attemptId: string, how: AttemptEndReason, reason: string, now: string): Job {
const { job, attempt } = this.requireCurrent(attemptId);
attempt.state = how;
attempt.endedAt = now;
attempt.endReason = reason;
job.assigneeId = job.leadId;
job.state = how === "lost" ? "lost" : "unassigned";
job.currentAttemptId = null;
return job;
}
finish(attemptId: string, actorId: string, now: string): Job {
const attempt = this.attempts.get(attemptId);
const job = attempt ? this.jobs.get(attempt.jobId) : undefined;
if (!attempt || !job) throw new Error("not_the_current_attempt");
if (job.state === "done" || job.state === "canceled") {
throw new Error("job_already_terminal");
}
if (attempt.state !== "running" || job.currentAttemptId !== attemptId) {
throw new Error("not_the_current_attempt");
}
if (actorId !== job.leadId) throw new Error("only_lead_may_finish_job");
attempt.state = "finished";
attempt.endedAt = now;
job.state = "done";
job.finishedAt = now;
return job;
}
latestCheckpoint(jobId: string): Checkpoint | null {
const list = this.checkpoints.filter((c) => c.jobId === jobId);
return list.length ? list[list.length - 1] : null;
}
private requireCurrent(attemptId: string): { job: Job; attempt: Attempt } {
const attempt = this.attempts.get(attemptId);
const job = attempt ? this.jobs.get(attempt.jobId) : undefined;
if (!attempt || !job || attempt.state !== "running" || job.currentAttemptId !== attemptId) {
throw new Error("not_the_current_attempt");
}
return { job, attempt };
}
}
# Hub guards for Durable Job (atomic job/attempt transitions + attempt fence)
from dataclasses import dataclass, field
from typing import Literal, Optional
@dataclass
class Job:
id: str
lead_id: str
assignee_id: str
state: Literal["unassigned", "working", "waiting", "lost", "done", "canceled"] = "unassigned"
current_attempt_id: Optional[str] = None
finished_at: Optional[str] = None
@dataclass
class Attempt:
id: str
job_id: str
number: int
worker_id: str
state: Literal["running", "finished", "handed_back", "lost", "replaced"] = "running"
from_checkpoint_id: Optional[str] = None
ended_at: Optional[str] = None
end_reason: Optional[str] = None
@dataclass
class Checkpoint:
id: str
job_id: str
attempt_id: str
saved_at: str
verified: list[dict[str, str]] = field(default_factory=list)
in_progress: Optional[str] = None
artifacts: list[dict[str, str]] = field(default_factory=list)
class HubError(Exception):
pass
class DurableJobHub:
def __init__(self) -> None:
self.jobs: dict[str, Job] = {}
self.attempts: dict[str, Attempt] = {}
self.checkpoints: list[Checkpoint] = []
def assign(self, job_id: str, worker_id: str, attempt_id: str) -> Attempt:
job = self.jobs.get(job_id)
if job is None:
raise HubError("unknown_job")
if job.state not in ("unassigned", "lost"):
raise HubError("job_not_assignable")
earlier = [a.number for a in self.attempts.values() if a.job_id == job_id]
latest = self.latest_checkpoint(job_id)
attempt = Attempt(
id=attempt_id,
job_id=job_id,
number=max(earlier, default=0) + 1,
worker_id=worker_id,
from_checkpoint_id=latest.id if latest else None,
)
self.attempts[attempt_id] = attempt
job.assignee_id = worker_id
job.state = "working"
job.current_attempt_id = attempt_id
return attempt
def save_checkpoint(self, attempt_id: str, cp: Checkpoint) -> Checkpoint:
job, _ = self._require_current(attempt_id)
cp.job_id = job.id
cp.attempt_id = attempt_id
self.checkpoints.append(cp)
return cp
def close_attempt(
self, attempt_id: str, how: Literal["lost", "handed_back", "replaced"], reason: str, now: str
) -> Job:
job, attempt = self._require_current(attempt_id)
attempt.state = how
attempt.ended_at = now
attempt.end_reason = reason
job.assignee_id = job.lead_id
job.state = "lost" if how == "lost" else "unassigned"
job.current_attempt_id = None
return job
def finish(self, attempt_id: str, actor_id: str, now: str) -> Job:
attempt = self.attempts.get(attempt_id)
job = self.jobs.get(attempt.job_id) if attempt else None
if not attempt or not job:
raise HubError("not_the_current_attempt")
if job.state in ("done", "canceled"):
raise HubError("job_already_terminal")
if attempt.state != "running" or job.current_attempt_id != attempt_id:
raise HubError("not_the_current_attempt")
if actor_id != job.lead_id:
raise HubError("only_lead_may_finish_job")
attempt.state = "finished"
attempt.ended_at = now
job.state = "done"
job.finished_at = now
return job
def latest_checkpoint(self, job_id: str) -> Optional[Checkpoint]:
matches = [c for c in self.checkpoints if c.job_id == job_id]
return matches[-1] if matches else None
def _require_current(self, attempt_id: str) -> tuple[Job, Attempt]:
attempt = self.attempts.get(attempt_id)
job = self.jobs.get(attempt.job_id) if attempt else None
if not attempt or not job or attempt.state != "running" or job.current_attempt_id != attempt_id:
raise HubError("not_the_current_attempt")
return job, attempt
# Hub guards for Durable Job (pure functional core)
defmodule DurableJobHub do
defstruct jobs: %{}, attempts: %{}, checkpoints: []
def assign(%DurableJobHub{} = hub, job_id, worker_id, attempt_id) do
with {:ok, job} <- Map.fetch(hub.jobs, job_id) |> or_err(:unknown_job),
true <- job.state in [:unassigned, :lost] || {:error, :job_not_assignable} do
earlier = for {_id, a} <- hub.attempts, a.job_id == job_id, do: a.number
latest = latest_checkpoint(hub, job_id)
attempt = %{
id: attempt_id,
job_id: job_id,
number: Enum.max(earlier, fn -> 0 end) + 1,
worker_id: worker_id,
state: :running,
from_checkpoint_id: latest && latest.id,
ended_at: nil,
end_reason: nil
}
updated_job = %{job | assignee_id: worker_id, state: :working, current_attempt_id: attempt_id}
{:ok, attempt, put_pair(hub, updated_job, attempt)}
end
end
def save_checkpoint(%DurableJobHub{} = hub, attempt_id, cp) do
with {:ok, job, _attempt} <- require_current(hub, attempt_id) do
saved = Map.merge(cp, %{job_id: job.id, attempt_id: attempt_id})
{:ok, saved, %{hub | checkpoints: [saved | hub.checkpoints]}}
end
end
def close_attempt(%DurableJobHub{} = hub, attempt_id, how, reason, now)
when how in [:lost, :handed_back, :replaced] do
with {:ok, job, attempt} <- require_current(hub, attempt_id) do
closed = %{attempt | state: how, ended_at: now, end_reason: reason}
next_state = if how == :lost, do: :lost, else: :unassigned
updated_job = %{job | assignee_id: job.lead_id, state: next_state, current_attempt_id: nil}
{:ok, updated_job, put_pair(hub, updated_job, closed)}
end
end
def finish(%DurableJobHub{} = hub, attempt_id, actor_id, now) do
with {:ok, attempt} <- Map.fetch(hub.attempts, attempt_id) |> or_err(:not_the_current_attempt),
{:ok, job} <- Map.fetch(hub.jobs, attempt.job_id) |> or_err(:not_the_current_attempt),
true <- job.state not in [:done, :canceled] || {:error, :job_already_terminal},
true <- (attempt.state == :running and job.current_attempt_id == attempt_id) || {:error, :not_the_current_attempt},
true <- actor_id == job.lead_id || {:error, :only_lead_may_finish_job} do
done_attempt = %{attempt | state: :finished, ended_at: now}
done_job = %{job | state: :done, finished_at: now}
{:ok, done_job, put_pair(hub, done_job, done_attempt)}
end
end
def latest_checkpoint(%DurableJobHub{checkpoints: cps}, job_id) do
Enum.find(cps, &(&1.job_id == job_id))
end
defp require_current(hub, attempt_id) do
with %{state: :running} = attempt <- Map.get(hub.attempts, attempt_id),
%{current_attempt_id: ^attempt_id} = job <- Map.get(hub.jobs, attempt.job_id) do
{:ok, job, attempt}
else
_ -> {:error, :not_the_current_attempt}
end
end
defp put_pair(hub, job, attempt) do
%{hub | jobs: Map.put(hub.jobs, job.id, job), attempts: Map.put(hub.attempts, attempt.id, attempt)}
end
defp or_err({:ok, val}, _err), do: {:ok, val}
defp or_err(:error, err), do: {:error, err}
end
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:
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
waitingandcanceledjob states. - Evidence-Backed Completion, Close-Out Triage & Tracked Answer — enforce the close-out gates required before marking a job done.