A2A 任务幂等与恢复:重复消息、断流与停滞任务

A2A 任务幂等与恢复:重复消息、断流与停滞任务

网络会断、客户端会重试、进程会重启。协议不会替您吸收这些故障:它给了 messageId、contextId 和两条恢复通道,把"恰好一次"的效果留给实现。这里给出把这三样东西用起来的模式,以及一套参考端点和探针——用业务执行计数验证这些模式,第 4 节展示的结果来自真实运行。

状态与操作的含义见Task 对象页 与Task 运行时指南 ;重启与重试的发布检查清单见生产就绪检查 第 5 节。

恢复决策树

连接中断或响应超时后,客户端先判断任务去到了哪里,再决定动作:

流中断 / 响应超时
  ├─ 任务已到终态(COMPLETED / FAILED / CANCELED / REJECTED)?
  │    └─ 是:GetTask 取终态与产出物,结束
  ├─ 订阅通道可用(capabilities.streaming)?
  │    └─ 是:SubscribeToTask 重连,从事件流继续
  │         └─ 服务端不支持从任意点续传时,以收到的事件为准,
  │            仅在实现提供稳定事件标识时去重,并用 GetTask 核对快照
  ├─ 只剩轮询?
  │    └─ GetTask 按退避轮询,直到终态或停滞判定
  └─ 停滞判定:超过业务上限仍停在 SUBMITTED / WORKING
       ├─ 客户端:CancelTask,或在新任务里重发请求(同 contextId)
       └─ 服务端:把任务转入 FAILED 并写明原因,不要永远 WORKING

不要把"流结束"当成"任务结束":连接断开只说明您不再看得到它,任务本身可能仍在服务端推进。

1. 重复消息:本文实现采用 messageId 作为幂等键

本文实现采用服务端消息去重:发送方生成 messageId,重发时保持该值;服务端在自己定义的去重范围与保留窗口内识别重复并返回登记结果。规范把这一点定为可选——“Send Message operations MAY be idempotent. Agents may utilize the messageId to detect duplicate messages”(§3.3.1)——对不做去重的服务端重发会把工作执行两次;依赖重试前先确认服务端策略。同一节还说明 Get 类操作天然幂等、CancelTask 幂等,需要拿主意的只有 Send。

场景客户端行为本文实现的服务端策略
超时后重发同一条消息原样重发,messageId 不变识别重复,返回首次处理结果
对话中继续(同一任务)新 messageId + taskId(可附匹配的 contextId)作为新输入推进任务
任务结束后补充需求同 contextId、不带 taskId 的新消息创建新任务(终态任务不可重启)
重试指向的任务已到终态不要再带该 taskId 重发;重做用同 contextId、新 messageId 开新任务UnsupportedOperationError:终态任务不再接受消息(§3.1.1)——上行的"原样重发回放"只适用于不携带终态 taskId 的消息

本文实现要点:

  1. 本文服务端把 (taskId 或 contextId, messageId) 作为幂等键,存储首次处理的结果指针(任务 ID、响应或错误);
  2. 幂等窗口覆盖"客户端放弃之前"的整个周期,不只覆盖几秒;
  3. 业务副作用(外部调用、写库)发生在幂等键登记之后。这个顺序能挡住"工作已做、回执丢失"时的第二次执行,但挡不住它的镜像——进程在登记与副作用之间崩溃时,键存在而工作未做。第 3 节 的扫描把这类工作显式判为 FAILED,重做交给新的 messageId;跨进程的恰好一次需要事务性存储。第 4 节 把这条缝隙真实跑了一遍;
  4. 重发只有落在同一 scope 才会命中幂等键。后续消息天然带 taskId;新对话的第一条消息应从一开始就携带 contextId(或由服务端对无 scope 的首条消息按 messageId 单独设窗),否则每次重发都会生成新上下文、被当作新工作各执行一次。参考端点对无 taskId 且无 contextId 的首条消息按 messageId 单独设窗;
  5. 需要跨消息的幂等时用 contextId:同一上下文的新任务可以携带上游业务键,由您的实现定义去重范围。

协议不保证业务层面的恰好一次——referenceTaskIds、contextId 只提供关联信息,去重策略由实现定义。这一点生产就绪检查 第 5 节同样列为发布边界。

2. 重复投递:接收侧的三个去重点

恢复路径上有三个位置会遇到"同一事件第二次到达":

位置去重依据
流事件(重连后)实现提供的稳定事件标识;协议未定义通用事件序号
推送通知实现约定的通知标识;仅任务 ID + 状态可能合并不同更新(见推送接收方加固 第 4 节)
产出物分块实现提供的分块标识;artifactId、append、lastChunk 本身不足以判重

append 和 lastChunk 表示聚合方式与结束边界,不是分块身份。重复分块需要实现约定的去重标识;无法识别时,用 GetTask 快照对账。

3. 重启恢复:给已接收任务一个结局

服务端重启后,已接收的任务只有两种可接受的结局:按产品契约继续,或以明确结果失败。实现模式:

启动 → 加载持久化的任务记录
  ├─ 幂等键登记过的任务 → 重放登记结果,不重跑副作用
  ├─ 已在执行的任务 → 恢复执行,或转 FAILED(原因写"服务重启")
  └─ 无法恢复的 → FAILED + 可读原因;绝不停回 WORKING 等一个不会来的执行器

把"重启后任务去哪了"写进产品契约,客户端才能决定重试还是放弃;这一点在生产就绪检查 第 5 节的检查表里对应第 3 项。第 4 节 运行的第 2 阶段展示了扫描的实际行为:登记与副作用之间崩溃后,已接收任务在重启时被判 FAILED,账本里该键仍是零执行,重做在新键上恰好执行一次。

4. 参考端点与探针的真实运行

重复执行的副作用恰恰藏在"看起来一样的响应"背后,所以这些探针不比较响应:它们统计只增账本里的业务执行次数,并核对记录的结果。被测端点是一个单文件 A2A JSON-RPC 服务,实现第 1 节的策略与第 3 节的恢复扫描。

本节的短路径:把下面两个文件——a2a-idempotency-reference.py 与 check-idempotency-recovery.sh——保存到同一目录,并在该目录内运行 bash check-idempotency-recovery.sh . work(需要 python3、curl、jq),逐行读 PASS/FAIL 直到最后的 summary:。断言统计的是 work/ledger.jsonl 里的执行次数;FAIL 行会写明被破坏的具体预期。先保存服务器:

#!/usr/bin/env python3
"""Reference A2A endpoint for idempotency and recovery probes (v1.0.1, JSON-RPC binding).

A single-file teaching server, not a production agent. It implements the policy of
the guide: (taskId or contextId, messageId) as the idempotency key, business side
effects recorded to an append-only ledger, task records persisted to a state file,
and a startup sweep that gives interrupted tasks a definite FAILED outcome.
Accepted work executes on its own thread from the moment the request is
registered; SSE handlers only observe and relay, so a dropped connection can
neither cancel nor skip the work.

Implemented methods (POST /, JSON-RPC 2.0):
  SendMessage (blocking), SendStreamingMessage (SSE), SubscribeToTask (SSE),
  GetTask. CancelTask and push notifications are not implemented;
  configuration/metadata are accepted and ignored.

Message text drives the scenarios (the business is a word counter):
  "please fail"  -> the business operation fails; the task ends FAILED
  "please crash" -> the key and task are persisted, then the process exits
                    before the business runs (the crash gap)
  "slowly"       -> the task stays WORKING for ~4 s before completing

Environment switches for the negative controls:
  A2A_DEDUP=off    skip the key registry: duplicates execute twice
  A2A_PERSIST=off  keep state in memory only: a restart forgets keys and tasks

Usage: a2a-idempotency-reference.py --port 9999 --state state.json --ledger ledger.jsonl
"""
from __future__ import annotations

import argparse
import copy
import datetime
import json
import os
import sys
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

LOCK = threading.RLock()
STATE = {"tasks": {}, "keys": {}}          # persisted shape
DONE: dict[str, threading.Event] = {}      # in-memory terminal events, not persisted
STATE_PATH = None
LEDGER_PATH = None
PERSIST = os.environ.get("A2A_PERSIST") != "off"
DEDUP = os.environ.get("A2A_DEDUP") != "off"

TERMINAL = ("TASK_STATE_COMPLETED", "TASK_STATE_FAILED", "TASK_STATE_CANCELED", "TASK_STATE_REJECTED")


def now() -> str:
    return datetime.datetime.now(datetime.timezone.utc).isoformat()


def log(message: str) -> None:
    print(f"[{datetime.datetime.now().strftime('%H:%M:%S')}] {message}", file=sys.stderr, flush=True)


# ---------------------------------------------------------------- state and ledger

def load() -> None:
    if PERSIST and os.path.exists(STATE_PATH):
        with open(STATE_PATH, encoding="utf-8") as fh:
            loaded = json.load(fh)
        STATE["tasks"] = loaded.get("tasks", {})
        STATE["keys"] = loaded.get("keys", {})
    # Startup sweep: every accepted task gets an outcome. In-flight tasks cannot
    # resume (the executor is gone), so they move to FAILED with a readable reason.
    for task in STATE["tasks"].values():
        if task["status"]["state"] not in TERMINAL:
            task["status"] = failed_status("interrupted by server restart; resend with a new messageId to redo the work")
    save()
    for task in STATE["tasks"].values():
        DONE[task["id"]] = threading.Event()
        DONE[task["id"]].set()


def save() -> None:
    if not PERSIST:
        return
    tmp = f"{STATE_PATH}.tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump({"tasks": STATE["tasks"], "keys": STATE["keys"]}, fh)
    os.replace(tmp, STATE_PATH)  # atomic on the same filesystem


def ledger(key: str, task_id: str, outcome: str, words: int | None) -> None:
    """Record one business execution. This file is what the probes assert against."""
    line = {"ts": now(), "key": key, "taskId": task_id, "outcome": outcome}
    if words is not None:
        line["words"] = words
    with open(LEDGER_PATH, "a", encoding="utf-8") as fh:
        fh.write(json.dumps(line) + "\n")
        fh.flush()


# ---------------------------------------------------------------- task helpers

def failed_status(reason: str) -> dict:
    return {
        "state": "TASK_STATE_FAILED",
        "timestamp": now(),
        "message": {
            "messageId": f"recovery-{uuid.uuid4()}",
            "role": "ROLE_AGENT",
            "parts": [{"text": reason}],
        },
    }


def snapshot(task: dict) -> dict:
    """The wire shape of a task, as a deep copy: internal bookkeeping fields never
    leave the server, and later mutations never leak into an earlier snapshot."""
    return copy.deepcopy({k: v for k, v in task.items() if k != "input"})


# ---------------------------------------------------------------- business operation

def run_business(text: str) -> tuple[str, int | None, str | None]:
    """Returns (outcome, words, artifact_text). The only place side effects happen."""
    if "please fail" in text:
        return "failed", None, None
    words = len(text.split(":", 1)[1].split()) if ":" in text else len(text.split())
    return "completed", words, str(words)


# ---------------------------------------------------------------- JSON-RPC plumbing

def rpc_error(code: int, message: str, reason: str, **metadata) -> dict:
    return {
        "jsonrpc": "2.0",
        "id": None,
        "error": {
            "code": code,
            "message": message,
            "data": [{
                "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                "reason": reason,
                "domain": "a2a-protocol.org",
                "metadata": {k: str(v) for k, v in metadata.items()},
            }],
        },
    }


# ---------------------------------------------------------------- send path

def prepare(params: dict):
    """Resolve, replay, or register one idempotency key. No side effects happen here.

    Returns (task, key, text, mode, error):
      mode "terminal"  task is done (replay or instant result); task is the answer
      mode "join"      a duplicate of work still in flight; wait on DONE[task.id]
      mode "run"       registered; the caller dispatches the business to its own
                       thread (blocking callers then wait on DONE; streaming
                       callers send the first event while it runs)
      mode "slow"      registered; as "run" but the work takes ~4 s
    """
    msg = params.get("message") or {}
    message_id = msg.get("messageId") or ""
    if not message_id:
        return None, None, None, None, rpc_error(-32602, "messageId is required", "INVALID_PARAMS")
    text = " ".join(p.get("text", "") for p in msg.get("parts", []) if isinstance(p, dict))

    with LOCK:
        task = None
        if msg.get("taskId"):
            task = STATE["tasks"].get(msg["taskId"])
            if task is None:
                return None, None, None, None, rpc_error(
                    -32001, "Task not found", "TASK_NOT_FOUND", taskId=msg["taskId"])
            if task["status"]["state"] in TERMINAL:
                # Messages cannot be accepted for terminal tasks (spec 3.1.1).
                return None, None, None, None, rpc_error(
                    -32004, "Task is in a terminal state", "UNSUPPORTED_OPERATION",
                    taskId=task["id"], state=task["status"]["state"])
            if msg.get("contextId") and msg["contextId"] != task["contextId"]:
                return None, None, None, None, rpc_error(
                    -32602, "contextId does not match the task's context", "INVALID_PARAMS")

        # Key scope: the task for follow-ups, the context for new work, and the
        # messageId alone for a first message that carries neither.
        scope = msg.get("taskId") or msg.get("contextId") or "*first-message*"
        key = f"{scope}/{message_id}"

        if DEDUP and key in STATE["keys"]:
            replay = STATE["tasks"][STATE["keys"][key]]
            if replay["status"]["state"] in TERMINAL:
                return snapshot(replay), key, text, "terminal", None
            return snapshot(replay), key, text, "join", None

        # Register the key and persist BEFORE any side effect. A crash after this
        # point leaves accepted work with an outcome of nothing yet — the startup
        # sweep turns that into an explicit FAILED, never into silent re-execution.
        context_id = msg.get("contextId") or (task["contextId"] if task else f"ctx-{uuid.uuid4().hex[:10]}")
        if task is None:
            task = {
                "id": f"task-{uuid.uuid4().hex[:12]}",
                "contextId": context_id,
                "input": text,
                "artifacts": [],
            }
            STATE["tasks"][task["id"]] = task
            DONE[task["id"]] = threading.Event()
        if DEDUP:
            STATE["keys"][key] = task["id"]
        task["status"] = {"state": "TASK_STATE_WORKING", "timestamp": now()}
        save()

        if "please crash" in text:
            log(f"crash injection: key {key} persisted, exiting before the business runs")
            os._exit(70)

        return snapshot(task), key, text, ("slow" if "slowly" in text else "run"), None


def complete(task_id: str, key: str, text: str) -> dict:
    """Run the business for a prepared task and return the final snapshot."""
    if "slowly" in text:
        time.sleep(4)  # outside the lock: slow work must not block other requests
    with LOCK:
        task = STATE["tasks"][task_id]
        outcome, words, artifact_text = run_business(text)
        ledger(key, task["id"], outcome, words)
        if outcome == "completed":
            task["artifacts"].append({
                "artifactId": f"artifact-{uuid.uuid4().hex[:10]}",
                "name": "word count",
                "parts": [{"text": artifact_text}],
            })
            task["status"] = {"state": "TASK_STATE_COMPLETED", "timestamp": now()}
        else:
            task["status"] = failed_status("business error (injected by 'please fail')")
        DONE[task["id"]].set()
        save()
        return snapshot(task)


def join(task_id: str) -> dict:
    """A duplicate of in-flight work: wait for the outcome, return the same task."""
    DONE[task_id].wait(timeout=30)
    with LOCK:
        return snapshot(STATE["tasks"][task_id])


def dispatch(task_id: str, key: str, text: str) -> None:
    """Start the business for a prepared task on its own thread.

    Execution begins when the request is accepted, not when a connection delivers
    an event: a stream cut before the first event still executes the work exactly
    once, and blocking callers simply wait on the same DONE event.
    """
    def worker() -> None:
        try:
            complete(task_id, key, text)
        except Exception as exc:  # an accepted task must still reach a terminal state
            with LOCK:
                task = STATE["tasks"].get(task_id)
                if task is not None and task["status"]["state"] not in TERMINAL:
                    task["status"] = failed_status(f"executor error: {exc}")
                    DONE[task_id].set()
                    save()
    threading.Thread(target=worker, daemon=True).start()


# ---------------------------------------------------------------- HTTP layer

class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *args):  # quiet; the ledger is the record that matters
        pass

    def do_POST(self) -> None:
        length = int(self.headers.get("Content-Length") or 0)
        request = json.loads(self.rfile.read(length) or b"{}")
        method = request.get("method", "")
        rid = request.get("id")
        params = request.get("params") or {}

        def respond(payload: dict) -> None:
            payload["id"] = rid
            body = json.dumps(payload).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def start_stream() -> None:
            """Open the SSE response; the connection closes when the handler returns."""
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Connection", "close")
            self.close_connection = True
            self.end_headers()

        def write_event(payload: dict) -> None:
            """One SSE event. A broken pipe means the client cut the stream."""
            self.wfile.write(f"data: {json.dumps({'jsonrpc': '2.0', 'id': rid, 'result': payload})}\n\n".encode())
            self.wfile.flush()

        def updates_of(task_id: str) -> list[dict]:
            """The artifact and status events of a finished task, in order."""
            with LOCK:
                task = STATE["tasks"][task_id]
                rest = [{"artifactUpdate": {
                    "taskId": task["id"], "contextId": task["contextId"], "artifact": artifact}}
                    for artifact in task["artifacts"]]
                rest.append({"statusUpdate": {
                    "taskId": task["id"], "contextId": task["contextId"], "status": task["status"]}})
            return rest

        def stream(first: dict | None, rest: list[dict]) -> None:
            try:
                start_stream()
                if first is not None:
                    write_event(first)
                for payload in rest:
                    write_event(payload)
            except (BrokenPipeError, ConnectionResetError):
                log("stream cut by the client; the task keeps running server-side")

        def stream_live(first: dict, task_id: str) -> None:
            """Send the first event now; terminal updates follow when they happen."""
            try:
                start_stream()
                write_event(first)
                DONE[task_id].wait(timeout=30)
                for payload in updates_of(task_id):
                    write_event(payload)
            except (BrokenPipeError, ConnectionResetError):
                log("stream cut by the client; the task keeps running server-side")

        if method in ("SendMessage", "SendStreamingMessage"):
            first, key, text, mode, error = prepare(params)
            if error is not None:
                respond(error)
            elif method == "SendMessage":
                # SendMessageResponse wraps the payload: result = {"task": ...}
                # (GetTask returns the Task itself; proto v1.0.1).
                if mode == "terminal":
                    respond({"jsonrpc": "2.0", "result": {"task": first}})
                elif mode == "join":
                    respond({"jsonrpc": "2.0", "result": {"task": join(first["id"])}})
                else:
                    dispatch(first["id"], key, text)  # execution does not need this connection
                    respond({"jsonrpc": "2.0", "result": {"task": join(first["id"])}})
            else:  # SendStreamingMessage: the task event goes out first, updates follow
                if mode == "terminal":
                    stream({"task": first}, [])
                else:
                    if mode != "join":
                        dispatch(first["id"], key, text)  # before any connection I/O
                    stream_live({"task": first}, first["id"])
            return

        if method == "GetTask":
            with LOCK:
                task = STATE["tasks"].get(params.get("id") or "")
                if task is None:
                    respond(rpc_error(-32001, "Task not found", "TASK_NOT_FOUND", taskId=params.get("id")))
                else:
                    respond({"jsonrpc": "2.0", "result": snapshot(task)})
            return

        if method == "SubscribeToTask":
            with LOCK:
                task = STATE["tasks"].get(params.get("id") or "")
                if task is None:
                    respond(rpc_error(-32001, "Task not found", "TASK_NOT_FOUND", taskId=params.get("id")))
                    return
                if task["status"]["state"] in TERMINAL:
                    respond(rpc_error(-32004, "Task is in a terminal state", "UNSUPPORTED_OPERATION",
                                      taskId=task["id"], state=task["status"]["state"]))
                    return
                current = snapshot(task)  # deep copy under the lock: one consistent moment
                task_id = task["id"]
            # The first event is the current Task, sent at subscription time (spec
            # 3.1.6) — not the stale state of a finished task.
            stream_live({"task": current}, task_id)
            return

        respond(rpc_error(-32601, "Method not found", "METHOD_NOT_FOUND", method=method))


def main() -> None:
    global STATE_PATH, LEDGER_PATH
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--port", type=int, default=9999)
    parser.add_argument("--state", required=True)
    parser.add_argument("--ledger", required=True)
    args = parser.parse_args()
    STATE_PATH = args.state
    LEDGER_PATH = args.ledger
    load()
    server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
    log(f"reference endpoint on 127.0.0.1:{args.port} "
        f"(dedup={'on' if DEDUP else 'off'}, persist={'on' if PERSIST else 'off'})")
    server.serve_forever()


if __name__ == "__main__":
    main()

业务是数词数,消息文本驱动场景:please fail 让业务操作失败;please crash 在幂等键登记并落盘之后、业务执行之前退出进程——第 1 节承认的那条缝隙;slowly 让任务保持 WORKING 四秒,便于在任务中途切断连接。有一条结构规则比任何单一场景都重要:请求被接受的那一刻,业务就被派发到自己的线程,先于任何连接 I/O,SSE 处理器只负责观察与转发。已接收任务的执行从不依赖送达它的那条连接是否存活。两个环境开关各破坏恰好一项保证,供负例使用:A2A_DEDUP=off 跳过键登记表,A2A_PERSIST=off 只把状态留在内存里。

下面的装置负责起停端点、在崩溃与重启场景中杀掉它,并从账本文件断言。保存为 check-idempotency-recovery.sh:

#!/usr/bin/env bash
# Assert the idempotency-and-recovery contract of an A2A endpoint by counting
# business executions, not by comparing responses. Runs the full matrix from the
# guide against the reference endpoint: success, duplicate, concurrent duplicate,
# failure and redo, the crash gap, restart persistence, and real connection cuts
# before the first event and mid-task — plus the two negative controls (dedup
# off, persistence off), which must be DETECTED.
#
# Usage: bash check-idempotency-recovery.sh <reference-dir> <work-dir>
# Exit 0 iff every assertion holds. Dependencies: curl, jq, python3.
set -uo pipefail

REF=${1:?reference dir with a2a-idempotency-reference.py}
WORK=${2:?work dir for state and ledger files}
BASE=${A2A_BASE_URL:-}
[ -n "$BASE" ] || BASE=http://127.0.0.1:9999
PORT=${BASE##*:}
PY="$REF/a2a-idempotency-reference.py"
STATE="$WORK/state.json"
LEDGER="$WORK/ledger.jsonl"
SRV_LOG="$WORK/server.log"
PASS=0; FAIL=0

ok()   { printf 'PASS  %s\n' "$1"; PASS=$((PASS+1)); }
bad()  { printf 'FAIL  %s\n' "$1"; FAIL=$((FAIL+1)); }
check(){ if [ "$2" = "$3" ]; then ok "$1 ($2)"; else bad "$1: expected $3, got $2"; fi; }

send() { # messageId context text [taskId] -> response JSON
  local mid=$1 ctx=$2 text=$3 tid=${4:-}
  local body="{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"SendMessage\",\"params\":{\"message\":{"
  body+="\"role\":\"ROLE_USER\",\"parts\":[{\"text\":\"$text\"}],\"messageId\":\"$mid\""
  [ -n "$ctx" ] && body+=",\"contextId\":\"$ctx\""
  [ -n "$tid" ] && body+=",\"taskId\":\"$tid\""
  body+="}}}"
  curl -s --max-time 20 -H 'Content-Type: application/json' -d "$body" "$BASE"
}
stream() { # same args, SendStreamingMessage; prints raw SSE lines
  local mid=$1 ctx=$2 text=$3 tid=${4:-}
  local body="{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"SendStreamingMessage\",\"params\":{\"message\":{"
  body+="\"role\":\"ROLE_USER\",\"parts\":[{\"text\":\"$text\"}],\"messageId\":\"$mid\""
  [ -n "$ctx" ] && body+=",\"contextId\":\"$ctx\""
  [ -n "$tid" ] && body+=",\"taskId\":\"$tid\""
  body+="}}}"
  curl -sN --max-time 20 -H 'Content-Type: application/json' -d "$body" "$BASE"
}
get_task() { curl -s --max-time 10 -H 'Content-Type: application/json' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"GetTask\",\"params\":{\"id\":\"$1\"}}" "$BASE"; }
cut_before_first_event() { # messageId context text — a SendStreamingMessage whose
  # connection dies before a single response byte is read (a real early cut; the
  # request itself is delivered, so the server has accepted the work)
  python3 - "$BASE" "$1" "$2" "$3" <<'PYEOF'
import json, socket, struct, sys
base, mid, ctx, text = sys.argv[1:5]
host, port = base.split("//")[1].rsplit(":", 1)
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "SendStreamingMessage",
                   "params": {"message": {"role": "ROLE_USER", "parts": [{"text": text}],
                                          "messageId": mid, "contextId": ctx}}}).encode()
head = ("POST / HTTP/1.1\r\nHost: %s:%s\r\nContent-Type: application/json\r\n"
        "Content-Length: %d\r\nConnection: close\r\n\r\n" % (host, port, len(body))).encode()
s = socket.create_connection((host, int(port)), timeout=5)
s.sendall(head + body)
# Abortive close (RST), not a graceful FIN: with a FIN the server's writes can
# still buffer and "succeed"; an RST makes the first write fail for real.
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
s.close()  # die before reading any response byte
PYEOF
}

executions() { grep -c "\"key\": \"$1\"" "$LEDGER" 2>/dev/null || true; }   # business count for one key
task_field() { printf '%s' "$1" | jq -r "$2"; }

start_server() { # [env assignments before the command]
  env "$@" python3 "$PY" --port "$PORT" --state "$STATE" --ledger "$LEDGER" 2>>"$SRV_LOG" &
  SRV_PID=$!
  for _ in $(seq 1 50); do curl -s -o /dev/null --max-time 1 "$BASE" && break; sleep 0.1; done
}
stop_server()  { [ -n "${SRV_PID:-}" ] && kill -9 "$SRV_PID" 2>/dev/null; wait "$SRV_PID" 2>/dev/null; SRV_PID=; }

trap stop_server EXIT
mkdir -p "$WORK"; : > "$LEDGER"; : > "$SRV_LOG"

echo "== phase 1: success, duplicate, concurrent, failure (fresh state) =="
rm -f "$STATE"; start_server

R=$(send k1 c-scenario1 "count words in: one two three")
check "success reaches COMPLETED" "$(task_field "$R" '.result.task.status.state')" "TASK_STATE_COMPLETED"
check "success artifact word count" "$(task_field "$R" '.result.task.artifacts[0].parts[0].text')" "3"
check "success executes the business once" "$(executions c-scenario1/k1)" "1"
T1=$(task_field "$R" '.result.task.id')

R=$(send k1 c-scenario1 "count words in: one two three")            # verbatim retry
check "duplicate replays the same task" "$(task_field "$R" '.result.task.id')" "$T1"
check "duplicate adds no business execution" "$(executions c-scenario1/k1)" "1"

send k2 c-scenario2 "count words in: one two three" >"$WORK/c1.json" &
P1=$!
send k2 c-scenario2 "count words in: one two three" >"$WORK/c2.json" &
P2=$!
wait "$P1" "$P2"
A=$(task_field "$(cat "$WORK/c1.json")" '.result.task.id'); B=$(task_field "$(cat "$WORK/c2.json")" '.result.task.id')
check "concurrent duplicates land on one task" "$([ "$A" = "$B" ] && echo same || echo "different ($A vs $B)")" "same"
check "concurrent duplicates execute once" "$(executions c-scenario2/k2)" "1"

R=$(send k3 c-scenario3 "please fail while you count words")
check "business failure ends FAILED" "$(task_field "$R" '.result.task.status.state')" "TASK_STATE_FAILED"
check "failed attempt is one recorded execution" "$(executions c-scenario3/k3)" "1"
T3=$(task_field "$R" '.result.task.id')
R=$(send k3 c-scenario3 "please fail while you count words")         # retry of a failure
check "retry of the failed message replays it" "$(task_field "$R" '.result.task.id')" "$T3"
check "retry of the failed message executes nothing" "$(executions c-scenario3/k3)" "1"
R=$(send k4 c-scenario3 "count words in: one two three")             # redo with a new messageId
check "redo with a new messageId completes" "$(task_field "$R" '.result.task.status.state')" "TASK_STATE_COMPLETED"
check "redo is its own single execution" "$(executions c-scenario3/k4)" "1"

echo "== phase 2: the crash gap (registered key, side effect never ran) =="
CTX=c-crash
send k5 "$CTX" "please crash before counting words" >"$WORK/crash.out" 2>&1
CRASH_RC=$?
if [ "$CRASH_RC" -eq 0 ] && [ -s "$WORK/crash.out" ]; then
  bad "crash injection: the server answered instead of dying"
else
  ok "crash injection: no response arrives (curl exit $CRASH_RC)"
fi
check "the crashed key has NO business execution" "$(executions "$CTX/k5")" "0"

start_server                                                        # restart on the same state
R=$(send k5 "$CTX" "please crash before counting words")            # same messageId
check "after restart the sweep FAILED the accepted work" "$(task_field "$R" '.result.task.status.state')" "TASK_STATE_FAILED"
check "replay of the crashed key still executes nothing" "$(executions "$CTX/k5")" "0"
R=$(send k6 "$CTX" "count words in: one two three")                 # redo with a new messageId
check "redo after the crash gap completes" "$(task_field "$R" '.result.task.status.state')" "TASK_STATE_COMPLETED"
check "redo after the crash gap executes once" "$(executions "$CTX/k6")" "1"

echo "== phase 3: restart keeps accepted outcomes =="
R=$(get_task "$T1")
check "a COMPLETED task survives the restarts" "$(task_field "$R" '.result.status.state')" "TASK_STATE_COMPLETED"
check "its artifact survived" "$(task_field "$R" '.result.artifacts[0].parts[0].text')" "3"
R=$(send k1 c-scenario1 "count words in: one two three")            # retry long after a restart
check "late duplicate replays without re-execution" "$(executions c-scenario1/k1)" "1"

echo "== phase 4: real connection cuts, then reconcile =="
echo "-- 4a: the connection dies before the first event --"
cut_before_first_event k7 c-cut-pre "slowly count words in: one two three four five"
R=$(send k7 c-cut-pre "slowly count words in: one two three four five")  # blocking replay
check "cut before the first event: the work still completed" \
  "$(task_field "$R" '.result.task.status.state')" "TASK_STATE_COMPLETED"
check "cut before the first event: the artifact is intact" \
  "$(task_field "$R" '.result.task.artifacts[0].parts[0].text')" "5"
check "cut before the first event: exactly one execution" "$(executions c-cut-pre/k7)" "1"
T7=$(task_field "$R" '.result.task.id')

echo "-- 4b: the connection dies after the first event, mid-task --"
curl -sN --max-time 2 -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"SendStreamingMessage","params":{"message":{"role":"ROLE_USER","parts":[{"text":"slowly count words in: one two three four five six"}],"messageId":"k8","contextId":"c-cut-mid"}}}' \
  "$BASE" >"$WORK/cut-mid.txt" 2>/dev/null
CUT_RC=$?
check "the mid-task cut is a real disconnect (curl exit 28)" "$CUT_RC" "28"
check "the cut client received exactly one event" "$(grep -c '^data: ' "$WORK/cut-mid.txt")" "1"
E1=$(sed -n 's/^data: //p' "$WORK/cut-mid.txt" | head -n 1)
T8=$(printf '%s' "$E1" | jq -r '.result.task.id')
check "the delivered first event is WORKING" "$(printf '%s' "$E1" | jq -r '.result.task.status.state')" "TASK_STATE_WORKING"
check "the delivered first event has no artifacts yet" "$(printf '%s' "$E1" | jq -r '.result.task.artifacts | length')" "0"

echo "-- 4c: SubscribeToTask mid-task: snapshot now, updates when they happen --"
SUB=$(curl -sN --max-time 15 -H 'Content-Type: application/json' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"SubscribeToTask\",\"params\":{\"id\":\"$T8\"}}" "$BASE")
S1=$(printf '%s' "$SUB" | sed -n 's/^data: //p' | head -n 1)
check "subscription first event is the task at subscription time" \
  "$(printf '%s' "$S1" | jq -r '.result.task.status.state')" "TASK_STATE_WORKING"
check "subscription first event carries no completed artifacts" \
  "$(printf '%s' "$S1" | jq -r '.result.task.artifacts | length')" "0"
check "subscription delivered the artifact update" "$(printf '%s' "$SUB" | grep -c 'artifactUpdate')" "1"
check "subscription ended COMPLETED" \
  "$(printf '%s' "$SUB" | sed -n 's/^data: //p' | tail -n 1 | jq -r '.result.statusUpdate.status.state')" "TASK_STATE_COMPLETED"

echo "-- 4d: reconcile the cut task --"
R=$(get_task "$T8")
check "reconciled task id unchanged" "$(task_field "$R" '.result.id')" "$T8"
check "reconciled task reached COMPLETED" "$(task_field "$R" '.result.status.state')" "TASK_STATE_COMPLETED"
check "reconciled artifact word count" "$(task_field "$R" '.result.artifacts[0].parts[0].text')" "6"
check "mid-task cut executed the business once" "$(executions c-cut-mid/k8)" "1"

echo "-- 4e: a terminal task refuses SubscribeToTask --"
SUBT=$(curl -s --max-time 10 -H 'Content-Type: application/json' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"SubscribeToTask\",\"params\":{\"id\":\"$T7\"}}" "$BASE")
check "terminal task refuses SubscribeToTask" "$(task_field "$SUBT" '.error.code')" "-32004"

stop_server

echo "== negative control A: A2A_DEDUP=off must be detected =="
rm -f "$STATE"; : > "$LEDGER"; start_server A2A_DEDUP=off
send nd1 c-neg "count words in: one two three" >/dev/null
send nd1 c-neg "count words in: one two three" >/dev/null
N=$(executions c-neg/nd1)
if [ "$N" -eq 2 ]; then ok "duplicate assertion catches it ($N executions, expected 1)"; else bad "dedup-off control: expected 2 executions, saw $N"; fi
stop_server

echo "== negative control B: A2A_PERSIST=off must be detected =="
rm -f "$STATE"; : > "$LEDGER"; start_server A2A_PERSIST=off
send np1 c-neg "count words in: one two three" >/dev/null
stop_server
start_server A2A_PERSIST=off
send np1 c-neg "count words in: one two three" >/dev/null
N=$(executions c-neg/np1)
if [ "$N" -eq 2 ]; then ok "restart assertion catches it ($N executions across restarts, expected 1)"; else bad "persist-off control: expected 2 executions, saw $N"; fi
stop_server

echo
echo "summary: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ]

在具备 python3、curl、jq 的环境运行:

$ bash check-idempotency-recovery.sh . work
== phase 1: success, duplicate, concurrent, failure (fresh state) ==
PASS  success reaches COMPLETED (TASK_STATE_COMPLETED)
PASS  success artifact word count (3)
PASS  success executes the business once (1)
PASS  duplicate replays the same task (task-b39223c0703d)
PASS  duplicate adds no business execution (1)
PASS  concurrent duplicates land on one task (same)
PASS  concurrent duplicates execute once (1)
PASS  business failure ends FAILED (TASK_STATE_FAILED)
PASS  failed attempt is one recorded execution (1)
PASS  retry of the failed message replays it (task-71dc2ba38d4e)
PASS  retry of the failed message executes nothing (1)
PASS  redo with a new messageId completes (TASK_STATE_COMPLETED)
PASS  redo is its own single execution (1)
== phase 2: the crash gap (registered key, side effect never ran) ==
PASS  crash injection: no response arrives (curl exit 52)
PASS  the crashed key has NO business execution (0)
PASS  after restart the sweep FAILED the accepted work (TASK_STATE_FAILED)
PASS  replay of the crashed key still executes nothing (0)
PASS  redo after the crash gap completes (TASK_STATE_COMPLETED)
PASS  redo after the crash gap executes once (1)
== phase 3: restart keeps accepted outcomes ==
PASS  a COMPLETED task survives the restarts (TASK_STATE_COMPLETED)
PASS  its artifact survived (3)
PASS  late duplicate replays without re-execution (1)
== phase 4: real connection cuts, then reconcile ==
-- 4a: the connection dies before the first event --
PASS  cut before the first event: the work still completed (TASK_STATE_COMPLETED)
PASS  cut before the first event: the artifact is intact (5)
PASS  cut before the first event: exactly one execution (1)
-- 4b: the connection dies after the first event, mid-task --
PASS  the mid-task cut is a real disconnect (curl exit 28) (28)
PASS  the cut client received exactly one event (1)
PASS  the delivered first event is WORKING (TASK_STATE_WORKING)
PASS  the delivered first event has no artifacts yet (0)
-- 4c: SubscribeToTask mid-task: snapshot now, updates when they happen --
PASS  subscription first event is the task at subscription time (TASK_STATE_WORKING)
PASS  subscription first event carries no completed artifacts (0)
PASS  subscription delivered the artifact update (1)
PASS  subscription ended COMPLETED (TASK_STATE_COMPLETED)
-- 4d: reconcile the cut task --
PASS  reconciled task id unchanged (task-3ebb99c5f8b2)
PASS  reconciled task reached COMPLETED (TASK_STATE_COMPLETED)
PASS  reconciled artifact word count (6)
PASS  mid-task cut executed the business once (1)
-- 4e: a terminal task refuses SubscribeToTask --
PASS  terminal task refuses SubscribeToTask (-32004)
== negative control A: A2A_DEDUP=off must be detected ==
PASS  duplicate assertion catches it (2 executions, expected 1)
== negative control B: A2A_PERSIST=off must be detected ==
PASS  restart assertion catches it (2 executions across restarts, expected 1)

summary: 40 passed, 0 failed

这段输出是上面两个文件的一次真实运行(macOS,Python 3.14、curl 8.7、jq 1.8,仅回环地址,2026-10-31)。任务 ID 每次运行都会变化,计数和状态不会。4a 的断连是 RST 强断(abortive close),让服务端的首次写真正失败而不是静默进缓冲;优雅 FIN 可能让执行与连接耦合的实现漏过这条探针。这 40 条断言对该端点确立:

  • **重复。**同一键的重复——先后或并发——只产生一条账本记录和一个任务;执行中的重复会加入正在运行的执行,而不是另起一次;
  • **失败与重做。**业务失败是明确的登记结果:重发同一 messageId 返回同一个 FAILED 任务、不新增执行,重做发生在同一上下文的新 messageId 上;
  • **崩溃缝隙。**按第 1 节承认的方式表现:登记与副作用之间崩溃后,账本里该键没有记录,启动扫描把已接收任务判为 FAILED,其重放不执行,新 messageId 把工作重做一次;
  • **重启。**已接受的结果经得起 kill -9:COMPLETED 任务与其产出物在重启后仍在,迟到的重复依旧回放、不重新执行;
  • **接收。**两个断点都不丢结果:连接在首事件之前死掉(RST 强断、未读任何字节)或在首事件之后、完成之前被切断(curl 超时退出),已接收的工作仍恰好执行一次,GetTask 把同一任务 ID 对账到 COMPLETED 及其产出物;
  • **重新订阅。**任务中途的 SubscribeToTask 以订阅那一刻的任务为首事件——WORKING、无产出物——即时发出而不是等工作结束,随后按发生顺序给出产出物与终态更新;
  • **终态。**终态任务以 -32004 拒绝订阅;
  • **负对照。**关闭登记表后重复断言看到两次执行;关闭持久化后重启断言看到重放再次执行——探针检测得到被破坏的保证,而不是空洞地通过;
  • **决定性。**两条断连探针还对照一个故意退化的变体验证过(业务回到流处理器内执行、订阅用浅拷贝):首事件前断连在 6 次尝试中 6 次让已登记任务停在 WORKING 且账本零执行(浅拷贝订阅则显示 WORKING 却带着已完成产出物),因此上面的断言是决定性的,不是空洞通过。

另外,端点发出的报文形状用 Task 运行时指南 第 4 节的轨迹校验器单独核对过:完整流、订阅流、断流和一次阻塞响应全部通过。采轨迹的方法与那里相同:sed -n 's/^data: //p' stream.txt > trace.jsonl。

这些运行不能确立的:

  • 关于您的服务端的任何结论。该端点是教学参考,去重策略、保留窗口和扫描行为由本指南选定;您自己的实现需要先有等价的业务记录,这些断言才有意义;
  • 外部副作用的恰好一次。账本是单进程自己的文件,追加并 flush 但不 fsync;跨进程或外部系统共享的工作需要事务性存储或业务侧去重——这正是协议留给实现的部分;
  • 生产级行为:发送由一把进程级锁串行化(生产服务端应把互斥范围收到幂等键粒度),每个已接收任务跑在一个无上限的守护线程上(生产服务端应使用有界执行器),事件不支持从任意偏移续传,推送通知与 CancelTask 未实现。

5. 观测:让停滞可见

  • 停滞告警:WORKING 超过业务 P99 时长仍无事件的任务数;命中时给出任务年龄分布与最近事件;
  • 终态分布:COMPLETED / FAILED / CANCELED / REJECTED 比例,FAILED 按原因聚类;
  • 重复率:命中幂等键的消息占比——它同时反映网络质量与客户端重试策略;
  • 恢复指标:重连后成功取回终态的比例、重启后任务被终结(而非悬挂)的数量。

字段命名与生产就绪检查 第 4 节的日志约定保持一致,任务 ID 只做关联、不做授权。

相关页面

版本与验证说明

协议表述依据固定的 A2A v1.0.1 规范 与同标签 a2a.proto 核对:Send Message MAY be idempotent、实现可用 messageId 检测重复(§3.3.1);向终态任务发消息返回 UnsupportedOperationError(§3.1.1);订阅首事件必须是当前 Task、终态任务拒绝 SubscribeToTask(§3.1.6);SendMessage 的响应由 result.task 包装,而 GetTask 直接返回 Task(proto oneof payload)。两者冲突时以 proto 为准(§1.4)。

第 4 节的参考端点与装置于 2026-10-31 完整运行(macOS,Python 3.14、curl 8.7、jq 1.8,仅回环地址):40 条断言全部通过,含首事件前的真实断连(RST 强断)、任务中途断连(curl 超时)、以订阅时刻为首事件的中途订阅,以及终态任务拒绝订阅;两个负例均被检出,采集的流与阻塞响应通过 Task 运行时指南的轨迹校验器。同样的断连探针还跑过一个故意退化的变体(业务在流处理器内执行、订阅用浅拷贝):首事件前断连在 6 次尝试中 6 次让已接收任务停在 WORKING 且账本零执行,退化订阅的首事件迟到约 3.3 秒且 WORKING 与已完成产出物同现——这正是上文断言被写成那样的原因。这是该参考实现在一台机器上的运行证据——不是您服务栈的证据,不是外部副作用的恰好一次,也不是生产行为。去重窗口、持久化、停滞阈值和事件去重标识仍由实现定义。同一装置于 2026-11-14 以 macOS 12.7.6 上的 Python 3.12.16(仅回环地址)复跑:40 通过、0 失败,计数与状态不变。

来源:A2A 数据结构 、任务的生命周期 。