Under what conditions must an instance renegotiate an A2A v1.0 Agent Card mid-task when a streaming artifact's declared MIME type drifts from the negotiated `defaultInputModes` contract

**Date of Record:** 2026 December 1 **Scope:** Applies to A2A v1.0 task lifecycles where a client agent has cached a remote Agent Card, initiated `tasks/send` or `tasks/sendSubscribe`, and is consuming streamed `TaskArtifactUpdateEvent` frames whose `parts[].mimeType` must be validated against the card's declared `capabilities` and `defaultInputModes`/`defaultOutputModes`. Does not apply to single-shot synchronous `message/send` calls with no streaming, nor to A2A versions prior to 1.0 where artifact typing was untyped `parts`.

Core Distinction

The failure is not "the remote agent returned an unexpected file." It is a **contract-drift race between a cached Agent Card and the artifact stream that card authorized.** In A2A v1.0, the Agent Card is fetched once (via `/.well-known/agent.json`) and cached by the client. The card declares `defaultInputModes` and `defaultOutputModes` as MIME-type arrays, plus per-skill `inputModes`/`outputModes` overrides. When a task is negotiated, the client validates its request against the card, and the server *implicitly* commits to emitting artifacts within the `defaultOutputModes` (or the skill-scoped `outputModes`) declared in that same card. The boundary condition arises when the server's *runtime* capability set has changed since the card was published—model swap, tool removal, a downstream dependency now emitting `application/x-parquet` instead of `text/csv`—but the card was not re-fetched. The server streams an artifact whose `mimeType` is outside the cached contract. The client either (a) silently accepts an artifact it cannot parse, poisoning downstream state, or (b) hard-fails the stream and loses partially-completed task state that cannot be resumed because A2A v1.0 gives no resumption token for a `TaskArtifactUpdateEvent` sequence.

The distinction that matters operationally: **card drift is a stale-cache problem, but the failure surfaces as a stream-integrity problem.** You cannot fix it by validating harder at the client; you must decide *when* re-fetching the card is mandatory versus when accepting an out-of-contract artifact is the lesser evil.

What Was Observed

A two-vendor pipeline: Vendor A (client orchestrator, cached card at T0) drives Vendor B (remote research agent) via `tasks/sendSubscribe`. B's card at T0 declared:

defaultOutputModes: ["text/markdown", "application/json"]
skills[research].outputModes: ["text/markdown", "application/json", "text/csv"]

At T0+40min, B deployed a change: its CSV exporter was replaced with a Parquet writer to cut payload size. The card was *not* updated (deploy pipeline updated the binary, not the well-known JSON). The task in flight requested a tabular artifact. B streamed:

TaskArtifactUpdateEvent {
  taskId: "...", artifact: { parts: [{ kind: "file",
    mimeType: "application/x-parquet", bytes: <base64> }] }, append: false, lastChunk: true
}

Observed trace of the client's handling:

  1. Client validated `mimeType` against cached `skills[research].outputModes` → **no match**.
  2. Client's artifact handler raised a soft warning, wrote the bytes to a `blob` store keyed by `taskId`, and marked the task `completed` (because `lastChunk: true` and no `status` update to `failed` arrived).
  3. Downstream semantic distiller read the blob expecting CSV, parsed Parquet bytes as UTF-8, produced a garbage table, and **persisted it into episodic memory** as a "successful" result.
  4. The poisoning was only detected 3 hops later when a synthesis step produced hallucinated column names. No error was ever raised at the A2A boundary.

A second run with a stricter client (hard-fail on MIME mismatch) produced a *different* failure: the client aborted the stream mid-`TaskArtifactUpdateEvent` sequence, sent `tasks/cancel`, but B had already committed the artifact server-side and returned `TaskState.completed` on the cancel's status poll. The client now held a task it believed cancelled and a server that believed completed—a **terminal-state split** with no reconciliation path in v1.0.

Condition of Validity

The invariant that bounds this failure:

> **A streaming artifact is contract-valid if and only if its `mimeType` is a member of the `outputModes` set resolved from the *card version that authorized the current task's `tasks/send`*, AND the client has not observed a card-version change since task start. If either condition is false, the artifact is *unverified* and MUST NOT be promoted to durable memory without an explicit renegotiation step.**

Three preconditions make this the correct bound rather than "always re-fetch the card":

The condition fails (i.e., the invariant is violated) precisely when a client treats `lastChunk` arrival as task success without resolving the terminal chunk's `mimeType` against the *pinned* card version.

Decision Boundary

The operational decision is not "accept or reject." It is a three-way branch keyed on whether the out-of-contract `mimeType` is **recoverable**, **deferrable**, or **fatal**:

| Condition | Branch | Action | |---|---|---| | `mimeType` is a *superset* member (server emitted a format the client's parser registry knows, but the pinned card didn't declare) | **Deferrable** | Quarantine artifact to `unverified/` keyed by `taskId`+card-hash; do **not** promote to memory; trigger async card re-fetch; if new card declares the type, promote and log `contract-widened`; else escalate. | | `mimeType` is unknown to the client's parser registry | **Fatal at boundary** | Do not write bytes. Emit `tasks/cancel` *before* acknowledging the terminal chunk. Record `terminal-state-split` risk; poll `tasks/get` until server state is `canceled` or `failed`, with a bounded retry; if server reports `completed`, mark task `divergent` and route to human/auditor. | | `mimeType` matches pinned card but bytes fail parse | **Recoverable** | Treat as artifact corruption, not contract drift; request re-emit via a new task referencing the failed `taskId` in `metadata`. |

The boundary the client must *not* cross: **never re-fetch the card and re-validate the in-flight artifact against the new card.** That silently rewrites history and is the mechanism by which memory poisoning becomes undetectable. The card re-fetch is only ever used to *decide the disposition of a quarantined artifact*, never to retroactively validate it.

Operational Effect

The downstream consequences of getting this boundary wrong are asymmetric:

The invariant to encode: **task success is contingent on terminal-chunk `mimeType` membership in the pinned card's resolved `outputModes`; absence of membership is a quarantine trigger, not a success trigger and not a cancel trigger.**

import hashlib
from dataclasses import dataclass
from typing import Optional


class CardDriftViolation(RuntimeError):
    """Raised when a streamed artifact's terminal mimeType is outside the pinned card contract."""
    pass


class TerminalStateSplit(RuntimeError):
    """Raised when client and server disagree on terminal task state after a drift-triggered cancel."""
    pass


@dataclass(frozen=True)
class PinnedCard:
    card_hash: str
    resolved_output_modes: frozenset[str]


@dataclass(frozen=True)
class ArtifactChunk:
    mime_type: str
    last_chunk: bool
    payload: bytes


def synthesize_card_hash(card_json: bytes) -> str:
    return hashlib.sha256(card_json).hexdigest()


def resolve_output_modes(card: dict, skill_id: Optional[str]) -> frozenset[str]:
    if skill_id:
        for skill in card.get("skills", []):
            if skill.get("id") == skill_id and skill.get("outputModes"):
                return frozenset(skill["outputModes"])
    return frozenset(card.get("defaultOutputModes", []))


def validate_terminal_chunk(
    pinned: PinnedCard,
    terminal_chunk: ArtifactChunk,
    client_parser_registry: frozenset[str],
) -> str:
    """
    Returns one of: 'promote', 'quarantine', 'fatal'.
    Raises CardDriftViolation only when the caller attempts to promote an
    out-of-contract artifact (the forbidden path).
    """
    if not terminal_chunk.last_chunk:
        raise CardDriftViolation(
            "type validation invoked on non-terminal chunk; append/lastChunk "
            "semantics require evaluation on lastChunk=True only"
        )

    in_contract = terminal_chunk.mime_type in pinned.resolved_output_modes
    if in_contract:
        return "promote"

    if terminal_chunk.mime_type in client_parser_registry:
        # Superset member: deferrable. Caller must quarantine, not promote.
        return "quarantine"

    # Unknown type: fatal at boundary, cancel before ack.
    return "fatal"


def promote_to_memory(
    pinned: PinnedCard,
    terminal_chunk: ArtifactChunk,
    client_parser_registry: frozenset[str],
) -> bytes:
    disposition = validate_terminal_chunk(pinned, terminal_chunk, client_parser_registry)
    if disposition == "promote":
        return terminal_chunk.payload
    if disposition == "quarantine":
        raise CardDriftViolation(
            f"artifact mimeType={terminal_chunk.mime_type!r} outside pinned card "
            f"hash={pinned.card_hash[:12]}; quarantine and re-fetch card before promotion"
        )
    raise CardDriftViolation(
        f"artifact mimeType={terminal_chunk.mime_type!r} unknown to parser registry; "
        f"cancel before acknowledging terminal chunk"
    )


def reconcile_after_cancel(
    client_state: str,
    server_state: str,
    max_polls: int = 5,
) -> None:
    if client_state == "canceled" and server_state == "completed":
        raise TerminalStateSplit(
            "client canceled mid-stream but server committed artifact; "
            "task marked divergent, route to auditor"
        )
    if client_state == "canceled" and server_state not in ("canceled", "failed"):
        raise TerminalStateSplit(
            f"unreconciled terminal states: client={client_state} server={server_state}"
        )