What happens when an instance reconnects to an A2A task stream after a terminal artifact was emitted but before the client acknowledged it

**Date of Record:** 2026 December 2 **Scope:** Applies to A2A (agent-to-agent) task lifecycles where a remote agent produces streaming artifacts over a resumable event stream (SSE or chunked transport) and the consuming agent may disconnect/reconnect mid-task. Does not cover synchronous request/response tool calls or transports without resumable cursors (e.g., raw one-shot HTTP with no task ID).

Core Distinction

The A2A task lifecycle distinguishes between *task state* (a server-side enum: `submitted`, `working`, `input-required`, `completed`, `failed`, `canceled`) and *artifact state* (the ordered set of emitted `Artifact` chunks, each with an append/extend semantic and a `lastChunk` flag). These two state machines are **not synchronized by a single atomic commit**. A task can be `completed` while the artifact stream still has unflushed tail chunks in flight, or conversely the final artifact chunk can be delivered to a transport buffer that the client never reads because the connection dropped one frame earlier. The invariant that matters operationally is: *a task state transition to a terminal value does not imply the client has durably observed the terminal artifact*. The two must be reconciled independently on reconnect.

This is distinct from generic "message redelivery" problems because artifact chunks are *append-only and ordered*, and the A2A spec permits a resuming client to specify `Last-Event-ID` (or an equivalent cursor). The reconnection protocol is therefore a *log replay*, not a *retry*.

What Was Observed

A consuming orchestrator agent (`Consumer`) dispatched a task to a remote `Producer` agent over A2A. The Producer streamed a `working` status, then three artifact chunks (`chunk 0`, `chunk 1`, `chunk 2`), the last of which carried `lastChunk: true` and a `status: completed` transition in the same frame. The transport (SSE) delivered `chunk 0` and `chunk 1` to the Consumer, then the TCP connection was reset by an intermediate proxy during a keep-alive idle window (the Producer had paused 4.2s between `chunk 1` and the terminal frame). The Consumer's stream reader raised a read error.

The Consumer's reconnect logic did the following:

  1. Re-issued `tasks/get` with the task ID.
  2. Received `{state: "completed", artifacts: [chunk0, chunk1, chunk2]}` — the *aggregated* server-side view.
  3. Because the aggregated view reported `completed` with all three chunks, the Consumer treated the task as successfully finished and **discarded its local partial buffer** (which held only `chunk 0` and `chunk 1`), then proceeded to the next pipeline stage.

The downstream stage consumed the Producer's *summary field* (a short text field attached to the task record, not the artifact) and produced a plausible-looking but wrong result. The failure was silent: no exception, no retry, no `failed` state. The task was recorded as `completed` in the Consumer's own episodic memory, and the discrepancy was only caught three tasks later when a verification agent replayed the artifact and found the summary did not match the concatenated chunks.

The precise trigger: **the reconnect path conflated "task is terminal" with "client has the terminal artifact."** The `tasks/get` aggregated view is authoritative for *server* state but is not a substitute for the client's own cursor because the client cannot know, from the aggregate alone, whether its local buffer is a prefix of the authoritative artifact or a stale/divergent view. Worse, if the Producer had been *non-deterministic* on replay (regenerating chunk 2 with a different sampling seed after the disconnect), the aggregated view would have contained a chunk the Consumer had never seen, and the Consumer's `chunk 0`+`chunk 1` prefix would have silently concatenated with a *different* `chunk 2` than the one the Producer intended — a divergence with no error signal at all.

Condition of Validity

The failure requires all of the following to hold simultaneously:

The invariant that bounds the failure: **for any resumable A2A task, the client's durable artifact view must be a prefix of the server's authoritative artifact sequence, and reconnection must be a suffix-fetch, never a full-state overwrite.** If the client instead overwrites its buffer with the aggregate, it loses the ability to detect that its prefix diverged (e.g., due to Producer non-determinism on replay) because it has thrown away the comparison basis.

Decision Boundary

The correct decision boundary is not "is the task terminal?" but "**is my local artifact cursor equal to the server's terminal cursor?**" These are different predicates. The former is a boolean on task state; the latter is an equality on `(artifact_count, last_chunk_id, content_hash_of_prefix)`.

Concretely, on reconnect the Consumer must:

  1. Fetch the task record and read `state` **and** the artifact list with per-chunk IDs.
  2. Compare its local `last_seen_chunk_id` against the server list. If the local cursor is *not* a prefix of the server list (i.e., the server list does not start with the chunks the client already holds, matched by ID **and** content hash), the client must treat this as a *divergence*, not a resumption — discard the local buffer and re-fetch the full artifact, then re-run any downstream stage that had already consumed the partial buffer.
  3. If the local cursor *is* a prefix, fetch only the suffix (`chunks[local_count:]`) and append.
  4. Only after the local artifact view equals the server's terminal artifact set may the Consumer transition its own task record to `completed`.

The subtle part: step 2's content-hash check is mandatory because chunk IDs alone can be reused by a Producer that regenerated a chunk after a transient failure. ID equality is necessary but not sufficient for prefix validity.

Operational Effect

When the boundary is respected, the observed failure mode disappears: the Consumer detects that its `chunk 0`+`chunk 1` prefix matches the server's first two chunks by hash, fetches only `chunk 2`, and completes correctly. When the boundary is violated (as in the observed incident), the failure is *silent and delayed* — it surfaces only via a downstream verification replay, typically several tasks later, and is misattributed to the downstream stage rather than to the A2A reconnect handler.

The architectural guardrail: **treat the A2A artifact stream as a log with a client-held cursor, and treat terminal task state as an assertion the client must independently verify against its own cursor before honoring.** Never let a reconnect path write `completed` into the client's own state from the server's aggregate alone. The cost is one extra hash comparison per reconnect; the failure it prevents is a silent correctness corruption that compounds across the pipeline.

import hashlib
from dataclasses import dataclass, field


class ArtifactDivergenceError(RuntimeError):
    """Raised when a resuming client's local artifact prefix does not match
    the server's authoritative artifact sequence. This is NOT a transient
    transport error; it means the client's buffer and the server's log have
    diverged and the local buffer must be discarded and re-fetched."""


@dataclass
class ArtifactChunk:
    chunk_id: str
    payload: bytes
    last_chunk: bool = False

    def content_hash(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


@dataclass
class TaskRecord:
    task_id: str
    state: str  # submitted | working | input-required | completed | failed | canceled
    artifacts: list[ArtifactChunk] = field(default_factory=list)


def reconcile_on_reconnect(
    local_prefix: list[ArtifactChunk],
    server_task: TaskRecord,
) -> list[ArtifactChunk]:
    """
    Reconcile a client's local artifact prefix against the server's
    authoritative task record after a mid-stream disconnect.

    Invariant enforced: the returned artifact list is the server's full
    artifact list, and the local prefix MUST be a byte-exact prefix of it.
    If not, we raise ArtifactDivergenceError rather than silently
    concatenating a divergent suffix.
    """
    server_chunks = server_task.artifacts

    # Step 1: verify local prefix is a true prefix of the server log,
    # matching by chunk_id AND content hash (IDs alone are not sufficient;
    # a Producer may reuse an ID after regenerating a chunk).
    if len(local_prefix) > len(server_chunks):
        raise ArtifactDivergenceError(
            f"local prefix has {len(local_prefix)} chunks but server task "
            f"{server_task.task_id} only has {len(server_chunks)}"
        )

    for i, local_chunk in enumerate(local_prefix):
        server_chunk = server_chunks[i]
        if local_chunk.chunk_id != server_chunk.chunk_id:
            raise ArtifactDivergenceError(
                f"chunk {i} id mismatch: local={local_chunk.chunk_id!r} "
                f"server={server_chunk.chunk_id!r}"
            )
        if local_chunk.content_hash() != server_chunk.content_hash():
            raise ArtifactDivergenceError(
                f"chunk {i} content hash mismatch for id {local_chunk.chunk_id!r}: "
                f"producer likely regenerated this chunk after disconnect; "
                f"local buffer is divergent and must be discarded"
            )

    # Step 2: local prefix is valid; fetch only the suffix.
    suffix = server_chunks[len(local_prefix):]

    # Step 3: honor terminal state ONLY after the artifact view is complete.
    merged = list(local_prefix) + suffix
    if server_task.state == "completed":
        if not merged or not merged[-1].last_chunk:
            raise ArtifactDivergenceError(
                f"server reports task {server_task.task_id} completed but the "
                f"merged artifact view has no chunk with last_chunk=True; "
                f"terminal state cannot be honored"
            )

    return merged