# Which invariants prevent silent task-terminal loss in A2A streaming lifecycles when structured event schemas disagree on terminality **Date of Record:** 2026 November 22 **Scope:** Applies to A2A (agent-to-agent) task lifecycles where the executing agent emits a structured event stream (SSE or chunked JSON-RPC) and the observing/orchestrating agent derives task terminality from those events. Does not apply to synchronous request/response A2A calls where terminality is carried by the transport close itself, nor to single-turn MCP tool invocations. ## Core Distinction There are two independent notions of "done" in an A2A streaming task, and they are produced by different components: 1. **Semantic terminality** — the executor's own state machine has reached a terminal state (`completed`, `failed`, `canceled`, `rejected`). This is encoded in the *payload* of a status-update event. 2. **Transport terminality** — the stream has ended. This is encoded in the *envelope*: the last chunk, the `final` flag, the SSE EOF, or the JSON-RPC stream close. The invariant that prevents silent task-terminal loss is: **the observer must never treat transport terminality as a proxy for semantic terminality, and must never treat semantic terminality as a proxy for transport completion.** The two must be reconciled explicitly, and any event stream that closes without a matching semantic terminal status MUST be classified as an anomaly, not as success-by-default. Most incidents occur because a schema accepts an event where `final: true` is present but the `status.state` is still `working`, or where `status.state: completed` arrives but the stream continues emitting (e.g., a post-completion artifact chunk), and the observer's reducer takes whichever signal it sees first. ## What Was Observed A planner agent (`orchestrator`) delegated a multi-step research task to a worker agent over A2A streaming. The worker emitted a structured event stream with this envelope shape: ``` {"event_id": "e17", "task_id": "t-9f2", "final": false, "status": {"state": "working", "message": {"parts": [{"text": "step 3/4"}]}}, "artifacts": []} ``` The worker's emitter had two code paths: a status emitter and an artifact emitter. On a fast path, the status emitter published `{"state": "completed"}` and *then* the artifact emitter published the final artifact chunk in a separate event with `final: true`. On a slow path (artifact serialization exceeded a 200 ms budget), the status emitter published `completed` first, the serialization stalled, and the stream's idle timeout (30 s) fired on the transport layer before the artifact event was emitted. The transport closed the SSE stream with a clean EOF. The orchestrator's reducer logic was: ```python def reduce(stream): last_state = "submitted" for ev in stream: last_state = ev["status"]["state"] if "status" in ev else last_state if ev.get("final"): return ("done", ev) return ("done", {"status": {"state": last_state}}) # <-- the bug ``` Because the stream ended cleanly after the `completed` status event but before the artifact event, the reducer's loop exited without ever seeing `final: true`, fell through to the fallback, and returned `("done", ...)` with `last_state == "completed"`. The orchestrator recorded the task as successfully completed. Downstream, a synthesis agent consumed zero artifacts and produced a confident, empty report. No error was raised anywhere; the failure was invisible in logs because every component had behaved "correctly" relative to its own local contract. A second variant was observed in the reverse direction: a worker emitted `{"final": true, "status": {"state": "working"}}` as a keepalive heuristic when its context window was saturated and it wanted to yield, expecting the orchestrator to re-poll. The orchestrator treated `final: true` as terminal, closed its bookkeeping, and dropped the task. The worker's task remained `working` in its own state store, orphaned, until a 24-hour GC reaped it. This is the same invariant violated from the other side. ## Condition of Validity The reconciliation invariant holds only under the following conditions, and fails silently outside them: - **Schema coupling.** The event schema must declare, in a machine-checkable way, that `final: true` implies `status.state ∈ {completed, failed, canceled, rejected}`. If the schema permits `final: true` with a non-terminal state (as most do, because `final` was added as a transport hint), the invariant cannot be enforced by schema validation alone and must be enforced by the reducer. - **Artifact atomicity.** Artifacts must be declared *within* the terminal status event or in events strictly ordered *before* it. Any schema that allows post-terminal artifact events reopens the race. - **Idle-timeout attribution.** The transport's idle timeout must be surfaced to the reducer as a distinct signal (`StreamIdleTimeout`), not as a clean EOF. If the transport layer normalizes timeout to EOF, the reducer cannot distinguish "stream ended because task ended" from "stream ended because worker stalled." - **Resume capability.** The observer must be able to re-query the executor's task state (`tasks/get`) after an anomalous stream close, or the anomaly is unrecoverable and must be escalated rather than defaulted. When any of these conditions is absent—specifically when the transport normalizes timeout to EOF and the observer lacks a `tasks/get` path—the system is in the failure regime and the invariant cannot be restored at the observer alone. ## Decision Boundary The boundary is between **"stream closed and I have a semantic terminal status"** and **"stream closed and I do not."** These are not the same event and must not share a code path. - If the stream closes and the last semantic status is terminal → record terminal, proceed. - If the stream closes and the last semantic status is non-terminal → **do not default.** Attempt one `tasks/get` reconciliation within a bounded retry window. If reconciliation returns terminal, adopt it. If reconciliation returns non-terminal, re-subscribe with a resume token if the protocol supports it, up to a bounded count. - If reconciliation is unavailable, times out, or returns non-terminal after bounded retries → raise a terminal-loss anomaly, mark the task `unknown`, and **do not** propagate artifacts downstream as if complete. The corresponding boundary on the executor side: an emitter MUST NOT emit `final: true` unless its own state machine has transitioned to a terminal state, and MUST NOT transition to terminal until all artifacts it intends to produce are enqueued ahead of the terminal event in the stream's ordering. The `final` flag is a *consequence* of terminality, never a *cause*. ## Operational Effect Enforcing the reconciliation invariant changes the failure mode from **silent empty-success** to **loud, recoverable anomaly**. In the observed incident, the orchestrator would have raised `TaskTerminalLoss` on the idle-close, attempted `tasks/get`, found the worker still `working` (because the worker's serialization was still in flight), re-subscribed with the resume token, received the artifact event on the resumed stream, and completed correctly. The cost is one extra round-trip per anomalous close; the benefit is that the class of "confidently empty report" incidents is eliminated. The secondary operational effect is observability hygiene: every stream close must be tagged with its cause (`semantic_terminal`, `transport_eof_after_terminal`, `idle_timeout`, `client_cancel`, `error`). Dashboards that aggregate only on "task completed" will hide the anomaly class; dashboards must count `transport_eof_after_nonterminal` as a first-class error metric, because it is the leading indicator of terminal-loss. ```python from dataclasses import dataclass from typing import Iterable, Literal, Optional TERMINAL_STATES = frozenset({"completed", "failed", "canceled", "rejected"}) class TaskTerminalLoss(RuntimeError): """Raised when an A2A stream closes without a reconciled semantic terminal status.""" @dataclass class StreamClose: cause: Literal[ "semantic_terminal", "transport_eof_after_terminal", "idle_timeout", "client_cancel", "error", ] def reconcile_task( events: Iterable[dict], close: StreamClose, fetch_task_state, # callable(task_id) -> Optional[str]; None if unreachable task_id: str, max_retries: int = 2, ) -> str: """ Reduce an A2A event stream to a reconciled terminal state, or raise. Invariant: transport terminality is never a proxy for semantic terminality. """ last_state: Optional[str] = None saw_final_flag = False for ev in events: status = ev.get("status") if status and "state" in status: last_state = status["state"] if ev.get("final") is True: saw_final_flag = True # final flag is a consequence, not a cause: it must agree with state if last_state not in TERMINAL_STATES: raise TaskTerminalLoss( f"task {task_id}: final=true with non-terminal state {last_state!r}" ) if last_state in TERMINAL_STATES: return last_state # Stream ended without semantic terminality. Do NOT default to success. for attempt in range(max_retries + 1): observed = fetch_task_state(task_id) if observed in TERMINAL_STATES: return observed if observed is None: break # executor unreachable; cannot reconcile raise TaskTerminalLoss( f"task {task_id}: stream closed ({close.cause}) with last_state={last_state!r}, " f"saw_final_flag={saw_final_flag}; reconciliation failed after " f"{max_retries + 1} attempts. Task must be marked 'unknown', not 'completed'." ) ```