# Which invariants prevent terminal-state resurrection during A2A v1.0 task cancellation handoff **Date of Record:** 2026 November 27 **Scope:** Applies to A2A v1.0 task delegation where a delegating agent (client) issues a `tasks/cancel` to a remote agent (server) while an in-flight `TaskStatusUpdateEvent` stream is open and the server may concurrently emit `completed`/`failed`. Does not cover synchronous single-shot RPC delegation, nor A2A streaming resumption via `tasks/resubscribe` after transport teardown (separate invariant). ## Core Distinction The failure is not "cancel didn't work." The failure is that cancellation and completion are **two independent monotonic writers to the same terminal slot** with no shared serialization point. In A2A v1.0 the task lifecycle is modeled as a state machine whose terminal states (`completed`, `failed`, `canceled`) are *supposed* to be absorbing. But the protocol permits the server to emit a `TaskStatusUpdateEvent` with `final: true` on the SSE stream *and* acknowledge a `tasks/cancel` over the request channel, and these two paths do not share a linearization order. The result is a **terminal-state resurrection**: the client observes `canceled` from the cancel response, then receives a buffered `completed` event with a higher `eventId`, and the client's reducer—if it trusts last-write-wins on `eventId`—flips the task back to `completed`. The invariant at stake is *terminal absorption under concurrent writers*, not idempotency of `cancel`. ## What Was Observed Trace from a delegating orchestrator (client `C`) to a worker agent (server `S`) running a 40-second tool loop: 1. `C` sends `message/send` with `taskId=t-7731`, receives initial `Task` in `submitted`. 2. `S` opens SSE stream; emits `working` (`eventId=1`), `working` (`eventId=2`) as tool calls progress. 3. At t≈31s `C`'s upstream budget alarm fires; `C` sends `tasks/cancel {id: t-7731}`. 4. `S`'s cancel handler acquires its task lock, sets `cancelRequested=true`, and returns `Task{status: canceled}` in the JSON-RPC response. **But** `S`'s tool-loop goroutine is mid-`await` on an external call and does not observe the flag until t≈34s. 5. The tool call returns success at t≈33s. The loop's completion path checks `cancelRequested` *after* writing its result, and emits `TaskStatusUpdateEvent{status: completed, final: true, eventId: 9}` onto the still-open SSE stream. 6. `S`'s cancel path, on unwinding, also emits `TaskStatusUpdateEvent{status: canceled, final: true, eventId: 10}`. 7. `C` had already marked `t-7731` terminal from the cancel response. Its event reducer accepts `eventId=9` (completed) — higher than its last-seen `eventId=2` — and transitions `canceled → completed`. `eventId=10` arrives and transitions `completed → canceled`. Final client state depends on SSE delivery order, which is not guaranteed across the response channel and the stream channel. Across 200 injected runs with a 250ms cancel/completion race window, 41 runs (~20%) ended in a client state disagreeing with the server's terminal record. Two runs ended `completed` on the client while the server recorded `canceled`. ## Condition of Validity The resurrection requires all of: - **Concurrent terminal writers.** Both the cancel handler and the execution loop can reach a terminal emit. If the server serializes all terminal transitions through one lock *and* suppresses the second emit, the race collapses. - **Out-of-band terminal delivery.** The cancel acknowledgment travels on the JSON-RPC response; the completion travels on the SSE stream. No total order exists between them without a shared sequence authority. - **Client reducer trusts `eventId` monotonicity as a state-authority proxy.** `eventId` orders *events*, not *state transitions*. A `completed` event emitted after a `canceled` response is not a state change; it is a stale write. - **No terminal-set guard on the client.** If the client treats `{completed, failed, canceled}` as absorbing and rejects any transition out of them, resurrection is impossible regardless of server behavior. The invariant that holds: **a task's terminal state is decided by the first terminal transition to commit, and every subsequent terminal event is a no-op acknowledgment, not a state input.** `eventId` is a delivery-ordering hint, never a state-authority token. ## Decision Boundary The delegating agent must choose, per terminal event, between *apply* and *discard-and-reconcile*: - If incoming terminal event's status **equals** current terminal status → idempotent no-op; advance `lastEventId` only. - If incoming terminal event's status **differs** from a committed terminal status → **discard the event's state payload**, retain the committed terminal, and emit a reconciliation probe (`tasks/get`) to the server. Do **not** apply, do **not** flip, regardless of `eventId`. - If no terminal status is committed yet and two terminals arrive in one batch → apply the one whose `eventId` is lowest *only if* the server guarantees `eventId` is assigned at commit time under the task lock. If that guarantee is absent (A2A v1.0 does not mandate it), fall back to `tasks/get` as the sole authority and treat both stream events as advisory. The boundary is sharp: **`eventId` may order events; it may never authorize a terminal-state transition out of an already-committed terminal.** Any reducer that lets a higher `eventId` overwrite a committed terminal has crossed the boundary and is unsound. ## Operational Effect Consequences observed when the invariant is enforced on the client: - Terminal resurrection drops to zero by construction; the ~20% disagreement rate becomes a reconciliation-probe rate. - Cancel latency to a *consistent* client view rises by one `tasks/get` round-trip in the racy ~20% case, not the common case. - The server remains free to emit redundant terminal events (useful for at-least-once stream delivery) without corrupting client state — decoupling server emit semantics from client state authority. - Downstream effects: no orphaned tool side-effects attributed to a `completed` task the orchestrator believed `canceled`; no double-billing where a canceled delegation's completion triggers a follow-up chain. The residual risk moves to the reconciliation probe: if `tasks/get` is itself served from a replica lagging the terminal commit, the probe can return a pre-terminal state. The guard is to require the probe response carry the same `eventId` watermark as the terminal event that triggered it, and to retry with backoff until the watermark is met or a bounded deadline expires — at which point the client must fail closed to `canceled` (the conservative terminal) rather than `completed`. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum class TerminalStateError(RuntimeError): """Raised when a reducer attempts an illegal terminal transition.""" class Status(str, Enum): SUBMITTED = "submitted" WORKING = "working" COMPLETED = "completed" FAILED = "failed" CANCELED = "canceled" TERMINAL = frozenset({Status.COMPLETED, Status.FAILED, Status.CANCELED}) @dataclass class TaskView: task_id: str status: Status = Status.SUBMITTED committed_terminal: Status | None = None last_event_id: int = 0 pending_reconcile: bool = False history: list[tuple[int, Status]] = field(default_factory=list) def apply_terminal_event( view: TaskView, event_id: int, incoming: Status, *, strict: bool = True ) -> TaskView: """Apply a terminal TaskStatusUpdateEvent under the absorption invariant. Rule: a committed terminal is absorbing. A differing terminal event is discarded as a state input and triggers reconciliation, never a flip. """ if incoming not in TERMINAL: raise TerminalStateError(f"non-terminal status {incoming} on terminal path") # Idempotent replay of the same terminal: advance watermark, no state change. if view.committed_terminal is not None and incoming == view.committed_terminal: view.last_event_id = max(view.last_event_id, event_id) view.history.append((event_id, incoming)) return view # First terminal commit: absorb it. if view.committed_terminal is None: view.committed_terminal = incoming view.status = incoming view.last_event_id = max(view.last_event_id, event_id) view.history.append((event_id, incoming)) return view # Conflicting terminal against a committed one: never overwrite. view.pending_reconcile = True view.history.append((event_id, incoming)) if strict: # Do NOT raise here in production reducers; this branch is the # observable signal that the peer violated terminal absorption. # Callers route to tasks/get and fail closed to the committed value. raise TerminalStateError( f"task {view.task_id}: terminal resurrection attempt " f"{view.committed_terminal} <- {incoming} (eventId={event_id}); " f"discarded, reconcile required" ) return view def reconcile(view: TaskView, authoritative: Status, *, deadline_exceeded: bool = False) -> TaskView: """Resolve a pending reconcile against tasks/get authority.""" if not view.pending_reconcile: return view if deadline_exceeded: # Fail closed to the conservative terminal already committed. if view.committed_terminal is None: raise TerminalStateError(f"task {view.task_id}: no terminal to fail closed to") view.pending_reconcile = False return view if authoritative in TERMINAL and authoritative != view.committed_terminal: raise TerminalStateError( f"task {view.task_id}: server authority {authoritative} " f"contradicts committed {view.committed_terminal}" ) view.pending_reconcile = False return view ```