Progress Heartbeat
A worker agent can stay online, keep its connection open, and emit cheerful "still working" status updates every few seconds — while quietly spinning in circles on the same stuck step for hours. By the time anyone notices, an entire day is gone.
Progress Heartbeat replaces generic liveness pings with structured, evidenced progress reports. Only a genuinely new step resets the job's clock. When reports stop arriving, the hub marks the worker's attempt lost, prompts the lead agent to assign a replacement from the last saved checkpoint, and rejects anything the replaced worker sends later.
Progress report
Why "still connected" is the wrong signal
When long-running agent work spans hours — whether auditing contracts, synthesizing large research corpora, running data backfills, or building software — failures rarely look like clean crashes. A worker's container can vanish without saying goodbye, or worse, its process can stay completely healthy while the agent repeats the same failed move over and over.
Standard infrastructure health checks only answer one question: is the process still reachable? Because a looping agent keeps its socket open and keeps emitting status traffic, a connection check reports green all day. The status board reads "working" until a human eventually asks why nothing has shipped.
Progress Heartbeat fixes this by shifting the signal from availability to evidenced progress, backed by three rules enforced in hub code:
- Only new, evidenced steps reset the progress timer. Each report carries evidence of a completed step and a content fingerprint; repeating the same step does not move the deadline forward.
-
Overdue attempts trigger automatic recovery. When no new step arrives by
next_due_atplus a short grace period, the hub marks the attemptlostand opens a reassignment question for the lead agent — never bothering the requester. - The current attempt acts as a fencing token. Every incoming report must name the job's current running attempt; late reports from a replaced worker are rejected so a zombie session cannot corrupt its replacement's work.
Why separate the connection clock from the progress clock? A disconnected machine should trigger fast reconnection checks within a couple of minutes, whereas a real step on a complex task might legitimately take twenty or thirty minutes. Running two independent clocks lets the hub catch dead machines quickly and catch live, connected agents that have stopped moving forward.
Architecture and participants
Progress Heartbeat builds directly on Durable Job: a
job outlives any single worker session, and each try at the job is recorded as a distinct
Attempt. The Hub runs two
checks — a report check on every incoming progress report and a periodic
overdue timer — while the requester stays out of the loop entirely.
Attempt. Reports each completed
step with concrete evidence and names its attempt_id on
every write.
reassignment question when an
attempt is marked lost, inspects the job, and assigns a replacement worker (or intervenes
if repeated replacements fail).
Attempt, briefed from the
last verified Checkpoint so work completed by Worker A
is preserved.
fingerprint, optional
checkpoint_id, and the next due time.
Execution flow
Toggle between the normal recovery flow — where Worker A stalls in a loop and Worker B picks up cleanly from the last checkpoint — and the zombie-report failure path — where Worker A misses the stop notice and tries to report completion after replacement.
Each evidenced step moves next_due_at forward. Once
Worker A stops making real progress, the overdue reminder and grace period run out, the
hub marks Attempt 1 lost and asks the lead agent to reassign, and Worker B finishes from
the last checkpoint without interrupting the requester.
Begins after step 9 of the normal flow: Attempt 1 is marked lost
and Worker B is actively running under Attempt 2.
Because the hub verifies job.current_attempt_id == attempt_id
on every write, Worker A's late report fails with
attempt_replaced and stores nothing. Worker B completes
the job cleanly under Attempt 2.
Shared resources: The hub's attempt fence keeps a replaced worker from mutating hub records. To also stop a zombie worker from pushing to a shared branch or overwriting shared files, pair this pattern with Resource Lease.
Concrete examples
Progress Heartbeat works wherever long-running work breaks into observable milestones with verifiable outputs — whether reviewing documents, running operational pipelines, or writing software.
Example 1 — 40-vendor contract renewal audit
No code or unit tests- Job
- Extract auto-renewal clauses and notice windows from 40 supplier agreements into one compliance table.
- Heartbeats
-
After every batch of 10 contracts,
Worker Asubmits acheckpointprogress report linking the updated compliance table snapshot. Each new table hash movesnext_due_atforward by 30 minutes. - Stall
-
On contract 21, a scanned addendum causes
Worker Ato loop endlessly re-reading the same page. Its runtime keeps sending "still analyzing" status pings, so connection checks stay green — yet no new table snapshot arrives. - Recovery
-
At +30 minutes the hub prompts
Worker A; after a 5-minute grace window it marks Attempt 1lostand asks the lead agent to reassign.Worker Bstarts Attempt 2 from contract 21 using the saved 20-contract checkpoint and finishes the audit without waking the requester.
Example 2 — Webhook delivery retry queue
Software engineering- Job
- Add automatic retries for failed customer webhook deliveries.
- Heartbeats
-
Worker Areports a plan at 10:20 a.m., a commit at 10:50 a.m., and a verified retry check at 11:15 a.m. Each report sets the next due time 30 minutes out, putting the next deadline at 11:45 a.m. - Stall & fence
-
A second check fails and
Worker Abegins editing the same function in circles. At 11:45 a.m. the hub requests progress; at 11:50 a.m. it marks Attempt 1lostand opens a reassignment question. The lead agent assignsWorker Bat 11:52 a.m. from the 11:15 a.m. checkpoint. - Late report
-
At 12:05 p.m.,
Worker Adeletes the failing check and reports the job done under Attempt 1. The hub rejects the report withattempt_replacedand tells it to stop.Worker Bfinishes cleanly at 12:40 p.m.
What this pattern is NOT — Short tasks or deliberate waits
Negative example- Scenario
- A 45-second single-call document summary, or a job that intentionally paused to wait for a reviewer's approval or a human's answer.
- Why skip it
- For a short one-shot call with no intermediate milestones, one overall deadline is simpler and catches the exact same failures. And for a job that stopped on purpose to wait on someone else, pause the progress timer and use Resumable Wait so a legitimate wait is never misclassified as a stall.
When to use and when to skip
Use Progress Heartbeat when
- Jobs run longer than a human or lead agent is actively watching them.
- A worker can disappear silently (container shutdown, session timeout) or spin in a live reasoning loop.
- The work naturally yields intermediate steps with checkable evidence (plans, artifacts, commits, checkpoints).
- Jobs are persisted independently of workers using Durable Job.
Skip it when
- The job is short enough that a single end-to-end deadline catches failures more simply.
- The job intentionally paused for external input or review — use Resumable Wait and suspend the progress clock.
- The work is one atomic, indivisible operation (such as a single long model call) with no distinct intermediate steps.
Data model and hub invariants
Progress Heartbeat defines one append-only table —
progress_reports — and reads
jobs, attempts, and
checkpoints from
Durable Job. When an attempt is marked lost, the hub
also opens a reassignment question defined by
Self-Contained Question.
Progress report belongs permanently to one
Attempt and optionally points to a
Checkpoint saved with that step.
Table: progress_reports
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique identifier for the accepted progress report. |
| attempt_id | uuid | NOT NULL, FK | References attempts(id); verified against jobs.current_attempt_id before insert. |
| kind | text | NOT NULL | CHECK (kind IN ('plan_step', 'commit', 'test_result', 'checkpoint')). |
| summary | text | NOT NULL | One-sentence statement of the completed step. |
| evidence | jsonb | NOT NULL | Pointer to verifiable proof (artifact snapshot, commit hash, run ID, or diff). |
| fingerprint | text | NOT NULL | Hash of the canonical evidence used to detect and ignore repeated steps. |
| checkpoint_id | uuid | NULLABLE, FK | References checkpoints(id) saved alongside this step, if any. |
| reported_at | timestamptz | NOT NULL | Timestamp stamped by the hub's own clock when the report is accepted. |
| next_due_at | timestamptz | NOT NULL | Deadline by which the hub expects the next new step from the same attempt. |
Seven hub invariants
-
01Reports are append-only and permanently bound to one attempt Database constraint
progress_reports.attempt_idisNOT NULLwith a foreign key toattempts(id), and accepted reports are never updated or deleted while the job is open. -
02Only the job's current running attempt may record progress Hub guard
reportrejects missing attempts withunknown_attemptand rejects any attempt that is no longerjobs.current_attempt_idor no longerrunning(includinglostandreplaced) withattempt_replaced. -
03Repeated fingerprints never advance the deadline Database constraint
A
UNIQUE (attempt_id, fingerprint)index ensures an attempt cannot reset its progress clock by re-submitting the same step. Duplicates returnrepeatedwithout changingnext_due_at. -
04Hub clock stamps times and caps requested wait extensions Hub guard
reported_atalways comes from the hub's clock.next_due_atadvances by the default progress timeout or a worker-declared slow-step window capped at the hub's maximum wait limit. -
05Attached checkpoint must belong to the same attempt Database constraint
When
checkpoint_idis present, a composite foreign key(attempt_id, checkpoint_id)referencingcheckpoints(attempt_id, id)— mirrored by the hub guardcheckpoint_attempt_mismatch— prevents cross-attempt checkpoint links. -
06Overdue check anchors on the newest report or attempt start Hub guard
A
runningattempt is overdue once the hub clock passes thenext_due_atof its latest report, or once the default progress timeout passes afterstarted_atif no report has arrived yet. -
07Marking lost and opening reassignment happen atomically Hub guard
mark_lostverifies the attempt is still current and still overdue (otherwise returningattempt_replacedorattempt_not_overdue), then in one transaction marks the attempt and joblost, clearscurrent_attempt_id, assigns the job back to the lead agent, and opens areassignmentquestion.
Reference implementation
The same progress report fence, overdue detector, and atomic loss handoff in TypeScript,
Python, and Elixir. A production hub wraps report and
mark_lost in database transactions.
-- Hub guards for Progress Heartbeat (enforced in code, never in prompts)
import Std.Data.HashMap
open Std (HashMap)
inductive StepKind where
| planStep | commit | testResult | checkpoint
deriving Repr, BEq, DecidableEq
inductive JobState where
| working | waiting | lost | done
deriving Repr, BEq, DecidableEq
inductive AttemptState where
| running | lost | replaced | finished
deriving Repr, BEq, DecidableEq
structure Job where
id : String
requestId : String
assigneeId : String
state : JobState
currentAttemptId : Option String
deriving Repr
structure Attempt where
id : String
jobId : String
state : AttemptState
startedAtSec : Nat
endedAtSec : Option Nat := none
deriving Repr
structure ProgressReport where
id : String
attemptId : String
kind : StepKind
summary : String
evidence : String
fingerprint : String
checkpointId : Option String
reportedAtSec : Nat
nextDueAtSec : Nat
deriving Repr
structure Question where
requestId : String
jobId : String
kind : String := "reassignment"
answererId : String
openedAtSec : Nat
deriving Repr
-- What a worker sends; `waitSec` is how long it expects until its next report.
structure StepInput where
id : String
kind : StepKind
summary : String
evidence : String
checkpointId : Option String := none
waitSec : Option Nat := none
inductive ReportResult where
| stored | repeated
deriving Repr, BEq, DecidableEq
inductive HubError where
| unknownAttempt | attemptReplaced | checkpointAttemptMismatch | attemptNotOverdue
deriving Repr, BEq, DecidableEq
def defaultTimeoutSec : Nat := 30 * 60
def gracePeriodSec : Nat := 5 * 60
def maxWaitSec : Nat := 2 * 60 * 60
-- Stands in for SHA-256 over canonical evidence JSON or a file tree hash
def hashEvidence (evidence : String) : String := "sha256:" ++ evidence.trimAscii.toString
structure Hub where
jobs : HashMap String Job := {}
attempts : HashMap String Attempt := {}
checkpoints : HashMap String String := {} -- checkpoint id -> attempt id
reports : List ProgressReport := []
questions : List Question := []
namespace Hub
-- The attempt and its job, if the attempt is still the job's live, running one.
def liveAttempt (hub : Hub) (attemptId : String) : Except HubError (Attempt × Job) := do
let some attempt := hub.attempts[attemptId]? | throw .unknownAttempt
let some job := hub.jobs[attempt.jobId]? | throw .attemptReplaced
unless job.currentAttemptId == some attemptId && attempt.state == .running do
throw .attemptReplaced
return (attempt, job)
def report (hub : Hub) (attemptId : String) (step : StepInput) (nowSec : Nat) :
Except HubError (ReportResult × Hub) := do
let _ ← hub.liveAttempt attemptId
if let some cpId := step.checkpointId then
unless hub.checkpoints[cpId]? == some attemptId do throw .checkpointAttemptMismatch
let fingerprint := hashEvidence step.evidence
if hub.reports.any (fun r => r.attemptId == attemptId && r.fingerprint == fingerprint) then
return (.repeated, hub)
let waitSec := min (step.waitSec.getD defaultTimeoutSec) maxWaitSec
let entry : ProgressReport := {
id := step.id, attemptId, kind := step.kind, summary := step.summary,
evidence := step.evidence, fingerprint, checkpointId := step.checkpointId,
reportedAtSec := nowSec, nextDueAtSec := nowSec + waitSec }
return (.stored, { hub with reports := entry :: hub.reports })
-- Due time from the latest report, or from the attempt's start if none yet.
def dueAt (hub : Hub) (attempt : Attempt) : Nat :=
let mine := hub.reports.filter (·.attemptId == attempt.id)
let latest := mine.foldl (init := none) fun best r =>
match best with
| some b => if r.reportedAtSec > b.reportedAtSec then some r else some b
| none => some r
match latest with
| some r => r.nextDueAtSec
| none => attempt.startedAtSec + defaultTimeoutSec
def overdue (hub : Hub) (nowSec : Nat) : List String :=
hub.attempts.values.filter (fun a => a.state == .running && hub.dueAt a < nowSec)
|>.map (·.id)
def markLost (hub : Hub) (attemptId leadId : String) (nowSec : Nat) : Except HubError Hub := do
let (attempt, job) ← hub.liveAttempt attemptId
if hub.dueAt attempt + gracePeriodSec > nowSec then throw .attemptNotOverdue
-- One transaction: mark attempt and job lost and open the reassignment question
let question : Question :=
{ requestId := job.requestId, jobId := job.id, answererId := leadId, openedAtSec := nowSec }
let attempt := { attempt with state := .lost, endedAtSec := some nowSec }
let job := { job with state := .lost, assigneeId := leadId, currentAttemptId := none }
return { hub with
attempts := hub.attempts.insert attemptId attempt,
jobs := hub.jobs.insert job.id job,
questions := question :: hub.questions }
-- An empty hub knows no attempts, so every report is refused.
theorem report_on_empty (a : String) (s : StepInput) (n : Nat) :
({} : Hub).report a s n = .error .unknownAttempt := by
simp [report, liveAttempt]; rfl
end Hub
// Hub guards for Progress Heartbeat (enforced in code, never in prompts)
type StepKind = "plan_step" | "commit" | "test_result" | "checkpoint";
interface Job {
id: string;
requestId: string;
assigneeId: string;
state: "working" | "waiting" | "lost" | "done";
currentAttemptId: string | null;
}
interface Attempt {
id: string;
jobId: string;
state: "running" | "lost" | "replaced" | "finished";
startedAtSec: number;
endedAtSec: number | null;
}
interface ProgressReport {
id: string;
attemptId: string;
kind: StepKind;
summary: string;
evidence: string;
fingerprint: string;
checkpointId: string | null;
reportedAtSec: number;
nextDueAtSec: number;
}
interface Question {
requestId: string;
jobId: string;
kind: "reassignment";
answererId: string;
openedAtSec: number;
}
const DEFAULT_TIMEOUT_SEC = 30 * 60;
const GRACE_PERIOD_SEC = 5 * 60;
const MAX_WAIT_SEC = 2 * 60 * 60;
class Hub {
private jobs = new Map<string, Job>();
private attempts = new Map<string, Attempt>();
private checkpoints = new Map<string, { attemptId: string }>();
private reports: ProgressReport[] = [];
private questions: Question[] = [];
report(
attemptId: string,
step: {
id: string;
kind: StepKind;
summary: string;
evidence: string;
checkpointId?: string | null;
waitSec?: number;
},
nowSec: number
): "stored" | "repeated" {
const attempt = this.attempts.get(attemptId);
if (!attempt) throw new Error("unknown_attempt");
const job = this.jobs.get(attempt.jobId);
if (!job || job.currentAttemptId !== attemptId || attempt.state !== "running") {
throw new Error("attempt_replaced");
}
if (step.checkpointId) {
const cp = this.checkpoints.get(step.checkpointId);
if (!cp || cp.attemptId !== attemptId) {
throw new Error("checkpoint_attempt_mismatch");
}
}
const fingerprint = hashEvidence(step.evidence);
const dup = this.reports.some(
(r) => r.attemptId === attemptId && r.fingerprint === fingerprint
);
if (dup) return "repeated";
const waitSec = Math.min(step.waitSec ?? DEFAULT_TIMEOUT_SEC, MAX_WAIT_SEC);
this.reports.push({
id: step.id,
attemptId,
kind: step.kind,
summary: step.summary,
evidence: step.evidence,
fingerprint,
checkpointId: step.checkpointId ?? null,
reportedAtSec: nowSec,
nextDueAtSec: nowSec + waitSec
});
return "stored";
}
overdue(nowSec: number): string[] {
const late: string[] = [];
for (const attempt of this.attempts.values()) {
if (attempt.state === "running" && this.dueAt(attempt) < nowSec) {
late.push(attempt.id);
}
}
return late;
}
markLost(attemptId: string, leadId: string, nowSec: number): void {
const attempt = this.attempts.get(attemptId);
if (!attempt) throw new Error("unknown_attempt");
const job = this.jobs.get(attempt.jobId);
if (!job || job.currentAttemptId !== attemptId || attempt.state !== "running") {
throw new Error("attempt_replaced");
}
if (this.dueAt(attempt) + GRACE_PERIOD_SEC > nowSec) throw new Error("attempt_not_overdue");
// Atomic transaction in Postgres: mark attempt + job lost and open question
attempt.state = "lost";
attempt.endedAtSec = nowSec;
job.state = "lost";
job.assigneeId = leadId;
job.currentAttemptId = null;
this.questions.push({
requestId: job.requestId,
jobId: job.id,
kind: "reassignment",
answererId: leadId,
openedAtSec: nowSec
});
}
private dueAt(attempt: Attempt): number {
const mine = this.reports.filter((r) => r.attemptId === attempt.id);
if (mine.length === 0) return attempt.startedAtSec + DEFAULT_TIMEOUT_SEC;
return mine.reduce((a, b) => (b.reportedAtSec > a.reportedAtSec ? b : a)).nextDueAtSec;
}
}
function hashEvidence(evidence: string): string {
// Production hubs use SHA-256 over canonical evidence JSON or file tree hash
return "sha256:" + evidence.trim();
}
# Hub guards for Progress Heartbeat (enforced in code, never in prompts)
from dataclasses import dataclass, field
import hashlib
from typing import Literal, Optional
DEFAULT_TIMEOUT_SEC = 30 * 60
GRACE_PERIOD_SEC = 5 * 60
MAX_WAIT_SEC = 2 * 60 * 60
@dataclass
class Job:
id: str
request_id: str
assignee_id: str
state: Literal["working", "waiting", "lost", "done"] = "working"
current_attempt_id: Optional[str] = None
@dataclass
class Attempt:
id: str
job_id: str
started_at_sec: int
state: Literal["running", "lost", "replaced", "finished"] = "running"
ended_at_sec: Optional[int] = None
@dataclass
class ProgressReport:
id: str
attempt_id: str
kind: Literal["plan_step", "commit", "test_result", "checkpoint"]
summary: str
evidence: str
fingerprint: str
reported_at_sec: int
next_due_at_sec: int
checkpoint_id: Optional[str] = None
class HubError(Exception):
pass
class Hub:
def __init__(self) -> None:
self.jobs: dict[str, Job] = {}
self.attempts: dict[str, Attempt] = {}
self.checkpoints: dict[str, str] = {}
self.reports: list[ProgressReport] = []
self.questions: list[dict[str, object]] = []
def report(
self,
attempt_id: str,
report_id: str,
kind: Literal["plan_step", "commit", "test_result", "checkpoint"],
summary: str,
evidence: str,
now_sec: int,
checkpoint_id: Optional[str] = None,
wait_sec: int = DEFAULT_TIMEOUT_SEC,
) -> Literal["stored", "repeated"]:
attempt = self.attempts.get(attempt_id)
if attempt is None:
raise HubError("unknown_attempt")
job = self.jobs.get(attempt.job_id)
if job is None or job.current_attempt_id != attempt_id or attempt.state != "running":
raise HubError("attempt_replaced")
if checkpoint_id is not None and self.checkpoints.get(checkpoint_id) != attempt_id:
raise HubError("checkpoint_attempt_mismatch")
fp = hashlib.sha256(evidence.encode("utf-8")).hexdigest()
if any(r.attempt_id == attempt_id and r.fingerprint == fp for r in self.reports):
return "repeated"
capped_wait = min(wait_sec, MAX_WAIT_SEC)
self.reports.append(
ProgressReport(
id=report_id,
attempt_id=attempt_id,
kind=kind,
summary=summary,
evidence=evidence,
fingerprint=fp,
checkpoint_id=checkpoint_id,
reported_at_sec=now_sec,
next_due_at_sec=now_sec + capped_wait,
)
)
return "stored"
def overdue(self, now_sec: int) -> list[str]:
return [
a.id
for a in self.attempts.values()
if a.state == "running" and self._due_at(a) < now_sec
]
def mark_lost(self, attempt_id: str, lead_id: str, now_sec: int) -> None:
attempt = self.attempts.get(attempt_id)
if attempt is None:
raise HubError("unknown_attempt")
job = self.jobs.get(attempt.job_id)
if job is None or job.current_attempt_id != attempt_id or attempt.state != "running":
raise HubError("attempt_replaced")
if self._due_at(attempt) + GRACE_PERIOD_SEC > now_sec:
raise HubError("attempt_not_overdue")
# Atomic transaction in Postgres: mark attempt + job lost and open question
attempt.state = "lost"
attempt.ended_at_sec = now_sec
job.state = "lost"
job.assignee_id = lead_id
job.current_attempt_id = None
self.questions.append(
{
"request_id": job.request_id,
"job_id": job.id,
"kind": "reassignment",
"answerer_id": lead_id,
"opened_at_sec": now_sec,
}
)
def _due_at(self, attempt: Attempt) -> int:
mine = [r for r in self.reports if r.attempt_id == attempt.id]
if not mine:
return attempt.started_at_sec + DEFAULT_TIMEOUT_SEC
return max(mine, key=lambda r: r.reported_at_sec).next_due_at_sec
# Hub guards for Progress Heartbeat (pure functional core)
defmodule ProgressHeartbeat do
@default_timeout 30 * 60
@grace_period 5 * 60
@max_wait 2 * 60 * 60
def report(state, attempt_id, step, now) do
attempt = state.attempts[attempt_id]
job = attempt && state.jobs[attempt.job_id]
cp_id = step[:checkpoint_id]
fp = fingerprint(step.evidence)
cond do
attempt == nil ->
{:error, :unknown_attempt}
job == nil or job.current_attempt_id != attempt_id or attempt.state != :running ->
{:error, :attempt_replaced}
cp_id != nil and state.checkpoints[cp_id] != attempt_id ->
{:error, :checkpoint_attempt_mismatch}
Enum.any?(state.reports, &(&1.attempt_id == attempt_id and &1.fingerprint == fp)) ->
{:ok, :repeated, state}
true ->
wait = min(Map.get(step, :wait, @default_timeout), @max_wait)
entry = %{
id: step.id,
attempt_id: attempt_id,
kind: step.kind,
summary: step.summary,
evidence: step.evidence,
fingerprint: fp,
checkpoint_id: cp_id,
reported_at: now,
next_due_at: DateTime.add(now, wait)
}
{:ok, :stored, update_in(state.reports, &[entry | &1])}
end
end
def overdue(state, now) do
for {id, %{state: :running} = attempt} <- state.attempts,
DateTime.compare(due_at(state, id, attempt), now) == :lt,
do: id
end
def mark_lost(state, attempt_id, lead_id, now) do
attempt = state.attempts[attempt_id]
job = attempt && state.jobs[attempt.job_id]
cond do
attempt == nil ->
{:error, :unknown_attempt}
job == nil or job.current_attempt_id != attempt_id or attempt.state != :running ->
{:error, :attempt_replaced}
DateTime.compare(DateTime.add(due_at(state, attempt_id, attempt), @grace_period), now) == :gt ->
{:error, :attempt_not_overdue}
true ->
question = %{
request_id: job.request_id,
job_id: attempt.job_id,
kind: :reassignment,
answerer_id: lead_id,
opened_at: now
}
next_state =
state
|> update_in([:attempts, attempt_id], &Map.merge(&1, %{state: :lost, ended_at: now}))
|> update_in(
[:jobs, attempt.job_id],
&Map.merge(&1, %{state: :lost, assignee_id: lead_id, current_attempt_id: nil})
)
|> update_in([:questions], &[question | &1])
{:ok, next_state}
end
end
defp due_at(state, attempt_id, attempt) do
state.reports
|> Enum.filter(&(&1.attempt_id == attempt_id))
|> Enum.max_by(& &1.reported_at, DateTime, fn -> nil end)
|> case do
nil -> DateTime.add(attempt.started_at, @default_timeout)
report -> report.next_due_at
end
end
defp fingerprint(evidence) do
:crypto.hash(:sha256, :erlang.term_to_binary(evidence))
|> Base.encode16(case: :lower)
end
end
Stall and fencing trace
Walking Example 2 (webhook delivery retry queue) through these guards shows how duplicate reports fail to move the deadline, how the overdue check triggers atomic reassignment, and how the attempt fence blocks Worker A's late report:
1. hub.report("attempt_1", { id: "rep_3", kind: "test_result",
summary: "Failed delivery is retried", evidence: "check=retry_after_failure@4be1f0c" }, "11:15:00Z")
-> ok: stored (next_due_at = 11:45:00Z)
2. hub.report("attempt_1", { id: "rep_4", kind: "test_result",
summary: "Failed delivery is retried", evidence: "check=retry_after_failure@4be1f0c" }, "11:30:00Z")
-> ok: repeated (same fingerprint; next_due_at stays 11:45:00Z)
3. hub.overdue("11:44:00Z") -> []
hub.overdue("11:46:00Z") -> ["attempt_1"] (progress report overdue; 5m grace begins)
4. hub.markLost("attempt_1", "lead_1", "11:50:00Z")
-> ok (attempt_1 = lost; job_webhook_retry.current_attempt_id = null; reassignment question opened)
Lead assigns worker_b -> attempt_2 starts from 11:15 checkpoint
5. hub.report("attempt_1", { id: "rep_5", kind: "plan_step",
summary: "Job is done", evidence: "commit=9d02c7a" }, "12:05:00Z")
-> error: attempt_replaced (fenced out; nothing stored; job untouched)
Tradeoffs and practical guidance
Progress Heartbeat turns unbounded silent stalls into bounded minutes, at the cost of a few deliberate engineering choices:
- Reporting overhead: every step report consumes a small amount of tokens and latency, and a healthy worker that forgets to emit progress gets replaced unnecessarily.
- Timeout tuning is a judgment call: too short a window replaces slow but productive workers; too long a window lets genuinely wedged jobs sit idle.
- Reports are still claims: fingerprinting stops identical replays, yet a clever looping agent can still fabricate distinct low-value steps unless evidence points to real external outputs.
Practical implementation notes
- Let the hub observe evidence directly where possible: when a worker pushes a commit, saves an artifact, or finishes a verified run, have the hub record the progress report automatically rather than relying on the worker to self-report.
-
Hash content, not metadata: for commits or document exports, compute
fingerprintover the resulting tree or content hash rather than a commit SHA or timestamp, so amending the same unchanged file twice cannot spoof progress. -
Allow bounded slow-step announcements: let a worker declare an upcoming
long build or dataset pass with a longer
next_due_at, capped by a strict hub maximum. -
Issue per-attempt credentials: even if the same worker agent is assigned
a new attempt later, binding auth tokens to
attempt_idblocks stale sessions immediately at the API boundary. - Pause the clock during deliberate waits and cap replacements: suspend the progress timer while a job holds an active Resumable Wait, and escalate to the lead agent to re-examine the job itself if three replacements stall in a row.
Known uses and related patterns
- Temporal Activity Heartbeats: Temporal activities emit heartbeats that may attach progress details for the next retry attempt; missing the heartbeat timeout fails the attempt so the retry policy can schedule a replacement.
-
AWS Step Functions
SendTaskHeartbeat: workers reset a task's heartbeat timer using a task token, and expired or closed tokens fail withTaskTimedOut(though the call carries only the token, not step evidence). - Kubernetes Node Heartbeats: nodes periodically report readiness leases so the node controller marks unreachable nodes unknown and evicts workloads after a grace window — illustrating classic availability heartbeats that this pattern extends to evidenced progress.
- Volgenic: separates connection-level lifecycle sweeps from per-attempt credentials so disconnected hosts are detected quickly and replaced agent launches cannot authenticate to report stale state.
-
Classic literature relatives: extends Unmesh Joshi's HeartBeat
from server availability to task progress, uses Martin Kleppmann's Fencing Token
idea via
attempt_id, and refines Azure's Scheduler Agent Supervisor by sliding the deadline forward on each verified step.
Related patterns
- Durable Job — defines the persistent
Job,Attempt, andCheckpointrecords that survive a lost worker. - Resumable Wait — handles a job that stops on purpose to wait for an external event, pausing the progress timer while waiting.
- Resource Lease — extends the attempt fence beyond hub records to shared files, branches, and environments.
- Context Handoff — assembles the replacement worker's briefing from the last checkpoint and accepted progress reports.
- Self-Contained Question — defines the
reassignmentquestion the hub opens for the lead agent on attempt loss.