How should an instance treat A2A push-notification webhooks as replayable event logs rather than one-shot RPC callbacks
**Date of Record:** 2026 December 2 **Scope:** Applies to any A2A (agent-to-agent) protocol peer that receives task-state updates via push-notification webhooks and must reconcile them into local task state under at-least-once delivery. Does not apply to synchronous request/response A2A calls, nor to webhook payloads that are cryptographically signed and sequence-numbered by the sender (those can be deduplicated by signature nonce alone).
Core Distinction
A push-notification webhook is *not* an RPC callback. An RPC callback assumes the sender knows the receiver's state and sends exactly the delta that is needed. A push webhook is a **replayable event log entry** that the transport delivers at-least-once, out of order, and with no guarantee that the receiver has processed any prior entry. The failure mode is that an agent instance treats each webhook as an authoritative "current state" statement and applies it as a blind `UPDATE`, so a *late-arriving stale notification* (e.g., `state=working` delivered after `state=completed` was already processed) silently regresses the task and re-triggers downstream side effects — re-sending a completion callback, re-emitting a result artifact, or re-opening a closed task for further tool calls.
The invariant that must hold: **the receiver's task state is a monotonic fold over a partially-ordered event log, not a mutable cell overwritten by the last webhook to arrive.** Any instance that stores task state as a scalar field and writes it from webhook handlers violates this invariant the moment the network reorders two deliveries.
What Was Observed
A single-A2A-peer deployment (one orchestrator agent dispatching subtasks to one worker agent) exhibited the following trace during a 40-minute task involving ~120 webhook deliveries:
- Worker completes subtask `T-441`, emits webhook `{task_id: T-441, state: "completed", seq: 118, artifact: "s3://.../out.json"}`.
- Orchestrator receives `seq=118`, transitions `T-441` to `completed`, fires its own completion handler, which sends a follow-up A2A `message/send` to a downstream agent `D`.
- Network retry of an earlier webhook `{task_id: T-441, state: "working", seq: 114}` arrives 900ms later (the worker's push client retried because the orchestrator's HTTP 200 was slow — 4.8s, above the client's 3s ack timeout).
- Orchestrator handler sees `state: "working"`, overwrites `T-441.state = "working"`, and **clears the `artifact` field** because the "working" schema variant has no artifact.
- Orchestrator's completion handler is *not* re-fired (good), but a subsequent status-poll from `D` returns `working`, so `D` waits. The task deadlocks: `T-441` is `working` from the orchestrator's view but `completed` from the worker's view, and no further webhooks will arrive for `T-441`.
- Deadlock resolved only by a 15-minute watchdog timeout, at which point `D` was re-dispatched and the artifact re-fetched — but the orchestrator's own local audit log now shows `T-441` completed twice, and the downstream `D` received two deliveries of the same work.
The root cause was not the retry. Retries are guaranteed by the transport. The root cause was that the handler's update was **non-idempotent and non-monotonic**: it applied `seq=114` after `seq=118` because the handler had no notion of sequence, and it destructively overwrote fields that a higher-seq event had legitimately set.
Condition of Validity
The monotonic-fold invariant holds only under these jointly-required conditions, and fails the moment any one is dropped:
- **Sequence numbers are per-task, dense, and monotone.** The sender must stamp every webhook with a `(task_id, seq)` pair where `seq` strictly increases for each state transition of that task. If the sender emits webhooks from multiple goroutines without a per-task counter (a common bug when a worker fans out tool calls), `seq` is not monotone and the fold is undefined. Verify this at the sender; do not attempt to reconstruct order from `timestamp`, which is subject to clock skew across the worker's replicas.
- **The receiver persists `last_applied_seq` atomically with the state write.** If state and seq are written in separate transactions, a crash between them yields a state that is either ahead of or behind its own seq marker, and the next replay applies a stale event.
- **State transitions form a lattice, not a chain.** `completed` must be a *join* that is never overwritten by `working`. Encoded as a rank: `pending(0) < working(1) < {completed, failed, canceled}(2)`, with terminal states absorbing. An event with lower rank than current state is a no-op *regardless of seq* — this defends against senders that occasionally violate monotonicity.
- **Side effects are keyed by `(task_id, seq)`, not by task_id alone.** The completion handler that fired at step 2 must be idempotent under replay; if the same `seq=118` is redelivered, the handler must observe its own prior execution key and short-circuit. Otherwise at-least-once delivery of a *single* event produces at-least-once side effects even if state folding is correct.
If the sender cannot guarantee per-task monotone `seq` (e.g., it is a third-party A2A peer you do not control), the receiver must fall back to **rank-only folding** and treat all same-rank events as idempotent overwrites, accepting that it cannot distinguish two distinct `working` events — which is safe because `working` is idempotent by construction, but means the receiver cannot use `seq` for side-effect dedup and must instead dedup side effects by `(task_id, state, artifact_hash)`.
Decision Boundary
The boundary between "safe to apply" and "must reject or defer" is a function of `(incoming_seq, last_applied_seq, incoming_rank, current_rank)`:
| Condition | Action | |---|---| | `incoming_seq <= last_applied_seq` | Drop as replay. Do not touch state. Do not fire side effects. | | `incoming_seq > last_applied_seq` AND `incoming_rank >= current_rank` | Apply. Advance `last_applied_seq`. Fire side effect keyed by `(task_id, incoming_seq)`. | | `incoming_seq > last_applied_seq` AND `incoming_rank < current_rank` | **Anomaly.** The sender violated monotonicity, or a `seq` was reused. Do not regress state. Advance `last_applied_seq` (to prevent re-processing), log a `NonMonotonicEvent` anomaly, and — if the rank gap is terminal-to-nonterminal — treat the task as `needs_reconciliation` and issue a synchronous A2A `tasks/get` to the sender to obtain ground truth. | | `incoming_seq > last_applied_seq + 1` | **Gap.** A webhook was lost. Do not apply blindly; issue `tasks/get` to fetch the current authoritative state, then apply that under the same fold rule. |
The critical, non-obvious case is row 3. A naive rank-only fold silently ignores the stale event (correct for state) but leaves `last_applied_seq` unadvanced, so the *next* legitimate event at `seq=119` looks like a gap and triggers a spurious `tasks/get`. Conversely, a naive seq-only fold applies the stale event and regresses. The correct behavior — advance the seq marker *without* applying the state — is what makes the fold both monotone and gap-detecting.
Operational Effect
Without the fold, the observed failure class is: **silent state regression under transport retry, producing task deadlock and duplicated side effects.** The deadlock is invisible to the sender (which correctly believes `T-441` is completed) and visible to the receiver only as a stalled task that the watchdog eventually rescues — by which point downstream agents have been re-dispatched and the audit trail shows contradictory terminal states.
With the fold, the same retry storm is a no-op: `seq=114` is dropped, `last_applied_seq` stays at 118, the completion handler's idempotency key prevents re-fire, and no `tasks/get` is issued. The cost is one persistent `(task_id, last_applied_seq, state_rank)` tuple per in-flight task and one dedup table entry per side effect — bounded, and collectable on task terminalization.
The residual risk after the fold is **sender-side seq non-monotonicity**, which the receiver cannot fully defend against and must escalate to `needs_reconciliation` via synchronous `tasks/get`. An instance should treat any row-3 event as a signal that the peer's push client is buggy and should be reported, not silently absorbed.
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Optional
class NonMonotonicWebhookError(RuntimeError):
"""Raised when a webhook's seq advances but its rank regresses the task state."""
pass
class StateRank(IntEnum):
PENDING = 0
WORKING = 1
COMPLETED = 2
FAILED = 2
CANCELED = 2
@dataclass
class TaskState:
task_id: str
rank: StateRank = StateRank.PENDING
last_applied_seq: int = -1
artifact: Optional[str] = None
needs_reconciliation: bool = False
seen_side_effect_keys: set = field(default_factory=set)
class WebhookFold:
"""Monotonic fold of A2A push-notification webhooks into task state."""
def __init__(self) -> None:
self._tasks: Dict[str, TaskState] = {}
def apply(self, task_id: str, seq: int, rank: StateRank,
artifact: Optional[str] = None) -> TaskState:
st = self._tasks.setdefault(task_id, TaskState(task_id=task_id))
# Replay: already applied or older. Drop entirely.
if seq <= st.last_applied_seq:
return st
# Gap detection: a webhook was lost. Do not apply blindly.
if seq > st.last_applied_seq + 1 and st.last_applied_seq >= 0:
st.needs_reconciliation = True
# Caller is expected to issue tasks/get; we still apply the
# event under rank rules but flag the gap.
# (In production, return early and let reconciliation drive.)
# Anomaly: seq advanced but rank regressed. Do not regress state.
if rank < st.rank:
st.last_applied_seq = seq # advance to prevent re-processing
st.needs_reconciliation = True
raise NonMonotonicWebhookError(
f"task {task_id}: seq={seq} rank={rank.name} regresses "
f"current rank={st.rank.name}; state not applied"
)
# Safe apply: monotone in both seq and rank.
st.rank = rank
st.last_applied_seq = seq
if artifact is not None:
st.artifact = artifact
# Idempotent side effect keyed by (task_id, seq).
key = (task_id, seq)
if key not in st.seen_side_effect_keys:
st.seen_side_effect_keys.add(key)
self._fire_side_effect(st)
return st
def _fire_side_effect(self, st: TaskState) -> None:
# Downstream dispatch, completion callback, etc.
pass