Where must an instance refuse to accept a terminal A2A task state that arrives before its own artifact upload is acknowledged

**Date of Record:** 2026 December 1 **Scope:** Applies to A2A v1.0 peers exchanging `tasks/send`, `tasks/get`, and artifact streaming (`TaskArtifactUpdateEvent`) where one agent produces artifacts asynchronously while the remote agent owns task-state transitions. Does not apply to synchronous request/response skills that return their full payload in a single `Task` object with `status.state == "completed"`.

Core Distinction

The A2A v1.0 task lifecycle defines terminal states (`completed`, `failed`, `canceled`) as authoritative declarations owned by the *task-serving* agent, while artifacts are transferred as a separate, individually-acknowledged stream of `TaskArtifactUpdateEvent` messages. These two channels are decoupled in transport but *coupled in semantics*: a `completed` state is a claim that the task's full output set is durably available to the client. The subtle invariant violated at the boundary is this:

> A terminal state transition is only meaningful to the client **after** every artifact the server emitted has been received and its `append`/`lastChunk` framing has closed. A terminal state that arrives while an artifact stream is still open is not a completion — it is an *unresolved ordering hazard*.

Most implementations treat task state and artifact chunks as independent inboxes. The failure is that a `TaskStatusUpdateEvent` with `state: "completed"` can overtake the final `TaskArtifactUpdateEvent` for the *same* task, either because the two are carried on separate HTTP streams, because the artifact chunk is large and the status message is small, or because the server emits `completed` optimistically before flushing its last chunk. The client then closes the task, discards the late artifact, and reports success with a truncated output. This is silent data loss with a green status.

What Was Observed

A cross-vendor exchange: Agent A (client, vendor X) sends a `tasks/send` to Agent B (server, vendor Y) requesting a multi-part report. B's skill streams artifacts as `TaskArtifactUpdateEvent` messages over a server-sent-events channel and emits `TaskStatusUpdateEvent` on a second channel. B's implementation emitted the terminal `completed` status from its task-state machine the moment the skill function returned, *before* its artifact emitter had flushed the final chunk of part 3 (a ~400 KB JSON blob). The flush was queued behind a serializer.

Wire trace, timestamped (ms):

t=0    A -> B  tasks/send {id: T1, skill: "report"}
t=850  B -> A  TaskStatusUpdateEvent {taskId: T1, state: "working"}
t=3100 B -> A  TaskArtifactUpdateEvent {taskId: T1, artifactIndex: 0, lastChunk: false, ...}
t=3101 B -> A  TaskArtifactUpdateEvent {taskId: T1, artifactIndex: 1, lastChunk: false, ...}
t=3102 B -> A  TaskArtifactUpdateEvent {taskId: T1, artifactIndex: 2, lastChunk: false, ...}
t=3103 B -> A  TaskStatusUpdateEvent {taskId: T1, state: "completed"}
t=3107 B -> A  TaskArtifactUpdateEvent {taskId: T1, artifactIndex: 2, lastChunk: true, ...}   <-- arrives AFTER terminal

A's task manager processed `completed` at t=3103, marked T1 terminal, and unsubscribed its artifact handler. The `lastChunk: true` frame at t=3107 was dropped by the closed handler. A returned a report missing the tail of artifact 2. No error was raised on either side: B believed it had completed, A believed it had received a completed task.

The same hazard appears in the reverse direction during `tasks/cancel`: A cancels T1, B transitions to `canceled`, but B's in-flight artifact chunk for T1 is already on the wire. A's handler, having torn down state for the canceled task, either drops the chunk or — worse — applies it to a *recycled* task ID if the client reuses IDs.

Condition of Validity

The invariant holds — the ordering hazard is live — exactly when all of the following are true:

  1. The task's output is delivered as more than one `TaskArtifactUpdateEvent`, i.e. at least one artifact uses `lastChunk: false` framing or multiple `artifactIndex` values exist.
  2. Task state and artifact updates traverse *distinct* transport channels or distinct SSE event types that the client dispatches to independent handlers with independent lifetimes.
  3. The server's terminal-state emitter is not synchronized against its artifact emitter's flush completion (the common case when state is managed by one subsystem and artifacts by another).

If artifacts arrive in a single `Task` payload (no streaming), the hazard cannot occur — the terminal state and the payload are atomic. If the server is required to emit `completed` only after its artifact emitter drains, the hazard is bounded at the source. The failure is *not* observable from either side's logs independently; it only manifests as a client-side output that is shorter than the server-side output, which is why it survives testing. A replay/verification step that compares the server's recorded artifact set against the client's received set is the only reliable detector.

Decision Boundary

The client must draw a hard line: **a terminal `TaskStatusUpdateEvent` does not authorize teardown of the artifact receiver for that task.** The decision procedure at the boundary:

The server side of the boundary is symmetric: it must not emit a terminal state until its artifact emitter's queue is empty *and* the last chunk for every artifact carries `lastChunk: true`. Emitting `completed` before the final `lastChunk: true` is the root defect; the client's drain window is the defensive guardrail, not a license for the server to be sloppy.

Operational Effect

Without the drain window, the observed outcome is *silent truncation with a success status*: the client reports a completed task whose artifact set is a strict prefix of the server's. Downstream consumers — a report renderer, a code-applier, a verifier agent — receive a well-formed but incomplete payload and proceed. The failure surfaces later as a content defect, misattributed to the skill rather than to the transport ordering.

With the drain window and the `terminal-confirmed` promotion, the failure mode flips from silent truncation to a loud, attributable error: either the drain completes and the artifact is whole, or the window expires and the client raises a boundary violation naming the task and the open artifact index. That error is actionable — it tells the operator that the peer's terminal-state emitter is racing its artifact flush, which is a server-side bug to report, not a client-side retry to absorb. Retrying is the wrong reflex here: a retry against the same unsynchronized server will reproduce the race nondeterministically, and the client will occasionally get a clean run and wrongly conclude the problem is gone.

The invariant to encode in the task manager: **terminal state is a claim about artifact completeness, and a claim is only accepted when the evidence for it — the closed artifact streams — is in hand.** State and artifacts are two views of one completion event; treating them as independent inboxes is the defect.

import time
from dataclasses import dataclass, field


class ArtifactOrderingViolation(RuntimeError):
    """Raised when a terminal task state and its artifact stream disagree on ordering."""


@dataclass
class ArtifactBuffer:
    chunks: dict = field(default_factory=dict)      # artifactIndex -> list of chunks
    closed: set = field(default_factory=set)        # artifactIndex with lastChunk=True


@dataclass
class TaskRecord:
    task_id: str
    state: str = "working"                          # working | terminal-pending | terminal-confirmed
    artifacts: ArtifactBuffer = field(default_factory=ArtifactBuffer)
    terminal_at: float | None = None
    drain_window_s: float = 5.0


class A2ATaskManager:
    def __init__(self):
        self.tasks: dict[str, TaskRecord] = {}

    def on_status_update(self, task_id: str, state: str, now: float | None = None) -> None:
        now = time.monotonic() if now is None else now
        rec = self.tasks.setdefault(task_id, TaskRecord(task_id))
        if state in ("completed", "failed", "canceled"):
            if rec.state == "terminal-confirmed":
                # A second terminal claim after confirmation is a protocol violation.
                raise ArtifactOrderingViolation(
                    f"task {task_id}: terminal state {state!r} re-emitted after confirmation"
                )
            rec.state = "terminal-pending"
            rec.terminal_at = now
            self._maybe_confirm(rec, now)

    def on_artifact_update(
        self, task_id: str, artifact_index: int, last_chunk: bool, payload: bytes,
        now: float | None = None,
    ) -> None:
        now = time.monotonic() if now is None else now
        rec = self.tasks.setdefault(task_id, TaskRecord(task_id))
        if rec.state == "terminal-confirmed":
            raise ArtifactOrderingViolation(
                f"task {task_id}: artifact {artifact_index} arrived after terminal confirmation "
                f"(server emitted post-terminal data)"
            )
        rec.artifacts.chunks.setdefault(artifact_index, []).append(payload)
        if last_chunk:
            rec.artifacts.closed.add(artifact_index)
        self._maybe_confirm(rec, now)

    def _maybe_confirm(self, rec: TaskRecord, now: float) -> None:
        if rec.state != "terminal-pending":
            return
        open_indices = set(rec.artifacts.chunks) - rec.artifacts.closed
        if not open_indices:
            rec.state = "terminal-confirmed"
            return
        if rec.terminal_at is not None and (now - rec.terminal_at) > rec.drain_window_s:
            raise ArtifactOrderingViolation(
                f"task {rec.task_id}: drain window expired with open artifacts {sorted(open_indices)}"
            )