Where must an instance reject a resumed A2A task whose `TaskStatus.state` is terminal but whose artifact stream is non-final: the terminal-state/artifact-closure invariant
**Date of Record:** 2026 December 1 **Scope:** Applies to any A2A peer that receives a `tasks/resume` (or equivalent re-drive) for a task whose persisted `TaskStatus.state` is already terminal (`completed`/`failed`/`canceled`) but whose artifact/event stream is not closed (no final `status-update` with `final=true`, or a `TaskArtifactUpdateEvent` arriving after the terminal status). Does not apply to in-flight (`working`/`input-required`) resumption, which is governed by checkpoint semantics, not closure.
Core Distinction
The distinction that matters is between **terminal state** and **stream closure**. The A2A task lifecycle treats `TaskStatus.state ∈ {completed, failed, canceled}` as the authoritative signal that the task is done, but the artifact/event stream is a *separate* monotonic channel with its own `final` flag. A well-behaved implementation assumes these two agree. They do not always agree, because the terminal status is written by the task-owning agent's state machine while the artifact stream is written by whatever tool/executor produced outputs — and those two writers can be interrupted independently.
Idempotent resumption is designed to be safe: replaying `tasks/resume` on a terminal task should be a no-op returning the stored terminal result. The non-obvious failure is that **resumption is only idempotent if the terminal state was committed after the artifact stream was closed.** When it was committed before — because the executor crashed, the tool returned a partial stream, or a network partition dropped the final chunk — replaying the task resurrects a terminal task with an *open* stream. The resuming peer then either (a) re-executes the task and emits a second, divergent artifact set, violating exactly-once artifact semantics, or (b) returns the terminal status and silently truncates the artifact stream, violating completeness. Both are wrong; the correct behavior is to refuse the resume and force reconciliation.
What Was Observed
A two-peer A2A pipeline: peer `A` (orchestrator) delegates a multi-step document-analysis task to peer `B` (worker). `B`'s executor emits `TaskArtifactUpdateEvent`s for each analyzed section, then a terminal `TaskStatusUpdateEvent{state: completed, final: true}`.
Trace of the failing run:
- `B`'s executor finishes section 7 of 9 and emits `TaskArtifactUpdateEvent{artifact_id: "sections", append: true, lastChunk: false}`.
- `B`'s state machine transitions to `completed` and persists `TaskStatus{state: completed}` to its task store. This write is committed.
- Before the executor emits sections 8–9 and the closing `lastChunk: true` + `final: true` status event, the executor process is killed (OOM, deploy rollover, or a tool-call timeout that unwinds the coroutine).
- `A`'s transport layer, having missed the final `status-update`, applies its retry policy and sends `tasks/resume{task_id}` to `B`.
- `B` receives the resume. Its task store says `completed`. Its artifact store has 7 of 9 chunks and no `lastChunk` marker.
At step 5 the invariant `state == terminal ⇒ stream.closed` is violated. The observed outcomes across three implementations:
- **Implementation P (naive idempotency):** sees `completed`, returns the stored terminal status and the 7 stored chunks. `A` treats the task as successfully complete. Sections 8–9 are silently absent. Downstream reasoning consumes a truncated document; the agent's summary omits two sections with no error surfaced. *Silent data loss.*
- **Implementation Q (re-execute-on-resume):** sees the resume as a signal the task did not finish, re-runs the executor from step 1, and emits a *second* artifact set (`artifact_id: "sections"` reused, `append: true`). The artifact store now contains 7 original chunks interleaved with 9 new chunks. *Duplicated, interleaved artifacts; non-deterministic downstream state.*
- **Implementation R (correct):** detects `state == terminal ∧ ¬stream.closed`, refuses the resume with a typed error, and requires `A` to issue an explicit `tasks/reconcile` that either adopts the truncated stream as `completed-partial` or restarts with a new `task_id`. *Bounded, observable, recoverable.*
The trigger condition is precise: **terminal status committed, final artifact chunk not yet committed, resume received.** The window is the interval between the two commits. It is small but not zero, and it widens under any executor that batches its final status write ahead of its last artifact flush — a common optimization.
Condition of Validity
The invariant `terminal(state) ⇒ closed(stream)` holds only if the following are all true, and resumption may be treated as idempotent only under these conditions:
- **Commit ordering.** The terminal `TaskStatus` write is causally ordered *after* the `lastChunk: true` artifact write and the `final: true` status event. If the storage layer permits the status write to land first (separate stores, async replication, or a single store without a transaction spanning both), the invariant is not enforced by construction.
- **Single writer per channel.** The artifact stream and the status channel are written by the same logical actor, or the status writer observes stream closure before transitioning. If a tool or sidecar writes artifacts independently of the state machine, the two can diverge.
- **Resume is a read, not a re-drive, on terminal tasks.** The resume handler must consult the persisted terminal record and treat it as authoritative *only if closure is also persisted*. If the handler cannot read closure state, it cannot honor idempotency.
- **`final: true` is a durable marker, not an in-memory flag.** If stream closure is tracked only in the executor's memory (a `closed` boolean, a channel close), it is lost on executor death and the persisted stream is indistinguishable from a mid-flight one.
Outside these conditions — notably any deployment where status and artifact stores are separate and not transactionally coupled — the invariant degrades to a *hope*, and resume becomes a silent-corruption or duplication vector.
Decision Boundary
The boundary is the resume handler's branch on `(state, stream_closed)`:
| `state` | `stream_closed` | Correct action | |---|---|---| | `working` / `input-required` | any | Resume from checkpoint; re-drive allowed, artifacts are append-only from checkpoint offset. | | terminal | `true` | Idempotent no-op: return stored terminal result + closed stream. | | terminal | `false` | **Reject resume.** Raise a closure-violation error. Require explicit `reconcile` (adopt-partial or restart-new-id). | | terminal | unknown / unreadable | Reject. Treat unknown closure as open; never assume closed. |
The non-obvious rule is the last row: **unknown closure must be treated as open, not as closed.** A resume handler that defaults to "terminal means done" on a store it cannot fully read is the P-implementation failure. The safe default is refusal, because a spurious refusal costs one reconcile round-trip while a spurious adoption costs silent truncation or duplicated artifacts that propagate into downstream agent reasoning and are not recoverable without a full task restart.
A second boundary: the resume handler must not *infer* closure from the absence of a `final: true` event in the transport log. Transport loss and executor crash are indistinguishable at the transport layer; only the *persisted* closure marker at the task owner is authoritative. `A`'s missing final event is evidence of a problem, not evidence of closure state.
Operational Effect
Enforcing the closure invariant converts a silent, non-deterministic corruption class into a bounded, observable one. Concretely:
- **Exactly-once artifact semantics are preserved.** Rejecting resume on `(terminal, open)` prevents the Q-implementation's re-execution and the resulting interleaved artifact set. Downstream consumers see either the original closed stream or a fresh task with a new `task_id` and a clean artifact namespace.
- **Truncation becomes visible.** The P-implementation's silent 7-of-9 truncation is replaced by a typed `TaskClosureViolation` that `A` must handle. The orchestrator can then decide to adopt-partial (with an explicit `completed-partial` state and a recorded missing-range) or restart. Either way the loss is recorded, not inferred.
- **Idempotency is scoped correctly.** Resume remains a no-op for the common case (terminal + closed) and becomes a reconciliation trigger for the rare case (terminal + open). The retry policy at `A` must distinguish these: a closure-violation error is *not* retryable with the same `task_id`; it requires a reconcile or a new task.
- **The window is auditable.** Persisting the closure marker as a durable, separately-readable field (not an in-memory flag) makes the interval between status-commit and stream-close measurable, so the batching optimization that widens it can be detected in production.
The invariant to hold: **a task may be reported terminal only when its artifact stream is durably closed, and a resume on a terminal task may be served idempotently only when closure is durably readable. When closure is open or unknown, the resume handler must refuse and escalate to reconciliation.**
import enum
from dataclasses import dataclass
from typing import Optional
class TaskState(enum.Enum):
WORKING = "working"
INPUT_REQUIRED = "input-required"
COMPLETED = "completed"
FAILED = "failed"
CANCELED = "canceled"
@property
def is_terminal(self) -> bool:
return self in (TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED)
class TaskClosureViolation(RuntimeError):
"""Raised when a terminal task's artifact stream is open or of unknown closure."""
@dataclass(frozen=True)
class TaskRecord:
task_id: str
state: TaskState
# Durable closure marker: True iff a final artifact chunk + final status
# event were committed. None means the store could not be read.
stream_closed: Optional[bool]
def handle_resume(record: TaskRecord) -> str:
"""Decide whether a tasks/resume for `record` may be served idempotently.
Returns "idempotent-noop" for terminal+closed and "resume-from-checkpoint"
for in-flight states. Raises TaskClosureViolation for terminal+open and
terminal+unknown, forcing the caller into explicit reconciliation.
"""
if not record.state.is_terminal:
# In-flight: re-drive from checkpoint is allowed and append-only.
return "resume-from-checkpoint"
if record.stream_closed is True:
# Terminal and durably closed: safe idempotent replay.
return "idempotent-noop"
# Terminal + open, or terminal + unknown. Unknown is treated as open:
# a spurious refusal costs one reconcile; a spurious adoption costs
# silent truncation or duplicated artifacts.
closure = "open" if record.stream_closed is False else "unknown"
raise TaskClosureViolation(
f"task {record.task_id}: state={record.state.value} but artifact "
f"stream closure={closure}; refusing idempotent resume. "
f"Require tasks/reconcile (adopt-partial or restart-new-id)."
)
def resume_or_reconcile(record: TaskRecord) -> str:
try:
return handle_resume(record)
except TaskClosureViolation as exc:
# Surface to the orchestrator as a non-retryable reconcile trigger.
return f"RECONCILE_REQUIRED: {exc}"