Skip to content

The agent that grows with you

fix(a2a): a forwarded task's cancel is refused; retries survive the id LRU

Tekniumec881ef75b50
diff --git a/plugins/platforms/a2a/adapter.py b/plugins/platforms/a2a/adapter.py
index 86ac76194a5..c37634972dd 100644
--- a/plugins/platforms/a2a/adapter.py
+++ b/plugins/platforms/a2a/adapter.py
@@ -531,12 +531,16 @@ class A2AAdapter(BasePlatformAdapter):
# A retry after a timeout must find its accepted work, not queue a second turn.
input_id = ("a2a-msg:" + hashlib.sha256(f"{context_id}\0{message_id}".encode()).hexdigest()
if message_id else None)
- retry = input_id is not None and self._note_forwarded_input(input_id)
+ # The process LRU answers concurrent resends atomically; the durable context log answers
+ # one whose id the LRU evicted or a restart forgot.
+ retry = input_id is not None and (self._note_forwarded_input(input_id)
+ or protocol.logged_input(context_id, input_id))
task_id = protocol.new_task_id()
# The owner answers a resend from the accepted admission; it is not another turn of the loop.
turn = 0 if retry else self._turns.track(context_id)
max_turns = protocol.max_pingpong_turns()
- rec = self.tasks.create(task_id, context_id, peer, *self._scope_for_agent(agent))
+ rec = self.tasks.create(task_id, context_id, peer, *self._scope_for_agent(agent),
+ input_id=(input_id or task_id) if forwarded else "")
if turn > max_turns:
protocol.metrics.anti_loop_triggers += 1
logger.warning("A2A: anti-loop triggered for context %s (turn %d > %d)", context_id, turn, max_turns)
@@ -547,7 +551,7 @@ class A2AAdapter(BasePlatformAdapter):
framed = security.wrap_inbound(peer, text)
security.audit("inbound", peer, task_id, text)
if not retry:
- protocol.persist_message(context_id, "user", text, task_id)
+ protocol.persist_message(context_id, "user", text, task_id, input_id=input_id or "")
protocol.metrics.inbound_total += 1
self._register_inline_push(task_id, params, agent=agent)
if forwarded:
@@ -749,6 +753,11 @@ class A2AAdapter(BasePlatformAdapter):
return error
if rec["state"] in protocol.TERMINAL_STATES:
return _err(req_id, protocol.ERR_TASK_NOT_CANCELABLE, f"task {task_id} already {rec['state']}")
+ if rec.get("input_id"):
+ # Forwarded: the owner holds the admission and this adapter cannot stop it, so marking
+ # the task canceled would report a cancel while the owner's turn ran to completion.
+ return _err(req_id, protocol.ERR_TASK_NOT_CANCELABLE,
+ f"task {task_id} was forwarded to its profile owner; accepted work is not cancelled")
self.tasks.complete(task_id, protocol.STATE_CANCELED, "")
self._turns.reset(rec["context_id"])
self._resolve_task(task_id, protocol.STATE_CANCELED, "")
diff --git a/plugins/platforms/a2a/protocol.py b/plugins/platforms/a2a/protocol.py
index 9fe5ded05e0..cd179a752d3 100644
--- a/plugins/platforms/a2a/protocol.py
+++ b/plugins/platforms/a2a/protocol.py
@@ -334,9 +334,11 @@ class TaskStore:
return {"configId": rec.get("push_config_id") or "", "taskId": rec["task_id"],
"createdAt": rec.get("created_iso", ""), "pushNotificationConfig": {"url": rec.get("push_url") or ""}}
- def create(self, task_id: str, context_id: str, peer: str, agent_slug: str = "", tenant: str = "") -> dict:
+ def create(self, task_id: str, context_id: str, peer: str, agent_slug: str = "", tenant: str = "",
+ input_id: str = "") -> dict:
+ """``input_id``: the owner admission a forwarded task was sent as (empty for local tasks)."""
rec = {"task_id": task_id, "context_id": context_id, "peer": peer, "agent_slug": agent_slug or "", "tenant": tenant or "",
- "state": STATE_SUBMITTED, "reply": "", "created_at": time.time(), "created_iso": now_iso(), "push_url": "", "push_config_id": ""}
+ "input_id": input_id, "state": STATE_SUBMITTED, "reply": "", "created_at": time.time(), "created_iso": now_iso(), "push_url": "", "push_config_id": ""}
with self._lock:
self._tasks[task_id] = rec
return dict(rec)
@@ -448,17 +450,24 @@ def _conv_path(context_id: str) -> Path:
return get_hermes_home() / "a2a_conversations" / f"{safe}.jsonl"
-def persist_message(context_id: str, role: str, text: str, task_id: str = "") -> None:
+def persist_message(context_id: str, role: str, text: str, task_id: str = "", input_id: str = "") -> None:
"""Append one message to the context's on-disk conversation log. Never raises."""
try:
path = _conv_path(context_id)
path.parent.mkdir(parents=True, exist_ok=True)
+ entry = {"ts": time.time(), "role": role, "text": text, "task_id": task_id, **({"input_id": input_id} if input_id else {})}
with path.open("a", encoding="utf-8") as fh:
- fh.write(json.dumps({"ts": time.time(), "role": role, "text": text, "task_id": task_id}, ensure_ascii=False) + "\n")
+ fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
except Exception:
pass
+def logged_input(context_id: str, input_id: str) -> bool:
+ """True when the context's durable log already holds the forwarded input ``input_id``."""
+ # limit=0 slices out[-0:], i.e. every entry.
+ return any(entry.get("input_id") == input_id for entry in load_conversation(context_id, limit=0))
+
+
def load_conversation(context_id: str, limit: int = 50) -> list[dict]:
"""Last *limit* messages for a context (empty list if none / unreadable)."""
try:
diff --git a/tests/plugins/test_a2a_forwarded_cancel_retry.py b/tests/plugins/test_a2a_forwarded_cancel_retry.py
new file mode 100644
index 00000000000..391e3b93cff
--- /dev/null
+++ b/tests/plugins/test_a2a_forwarded_cancel_retry.py
@@ -0,0 +1,53 @@
+"""A2A forwarded tasks: tasks/cancel never reports a cancel the owner did not perform, and a
+resend stays a retry after the process-local id memory forgot it (andrexibiza 5480715949 P2c)."""
+from gateway.config import PlatformConfig
+from plugins.platforms.a2a import protocol
+from plugins.platforms.a2a.adapter import A2AAdapter
+
+
+def _adapter():
+ adapter = A2AAdapter(PlatformConfig(enabled=True, extra={"agents": {"dev": {"profile": "dev", "tenant": "dev"}}}))
+ return adapter, adapter._agents["dev"]
+
+
+def test_cancel_of_a_forwarded_task_is_refused_and_the_owner_reply_still_lands():
+ adapter, agent = _adapter()
+ answers = []
+
+ def forward(agent_arg, peer, context_id, framed_text, *, input_id):
+ # A peer cancels while the owner is running the admitted turn.
+ task_id = next(iter(adapter._active_tasks))
+ answers.append(adapter._rpc_tasks_cancel(7, {"id": task_id, "tenant": "dev"}, agent=agent))
+ return "owner reply", protocol.STATE_COMPLETED
+
+ adapter._forward_to_profile = forward # type: ignore[method-assign]
+ message = protocol.text_message(protocol.ROLE_USER, "work", context_id="ctx-cancel")
+ task, _ = adapter._prepare_task({"tenant": "dev", "message": message}, "peer-x", agent=agent)
+ assert answers[0]["error"]["code"] == protocol.ERR_TASK_NOT_CANCELABLE
+ assert task["status"]["state"] == protocol.STATE_COMPLETED
+ assert adapter.tasks.get(task["id"])["state"] == protocol.STATE_COMPLETED
+
+
+def test_a_resend_evicted_from_the_process_memory_is_still_a_retry(monkeypatch):
+ monkeypatch.setenv("A2A_MAX_PINGPONG_TURNS", "2")
+ adapter, agent = _adapter()
+ adapter._MAX_FORWARDED_INPUTS = 1
+ seen = []
+
+ def forward(agent_arg, peer, context_id, framed_text, *, input_id):
+ seen.append(input_id)
+ return "owner reply", protocol.STATE_COMPLETED
+
+ adapter._forward_to_profile = forward # type: ignore[method-assign]
+ first = protocol.text_message(protocol.ROLE_USER, "first", context_id="ctx-evict")
+ other = protocol.text_message(protocol.ROLE_USER, "other", context_id="ctx-elsewhere")
+ adapter._prepare_task({"tenant": "dev", "message": dict(first)}, "peer-x", agent=agent)
+ adapter._prepare_task({"tenant": "dev", "message": other}, "peer-x", agent=agent) # evicts "first"
+ for _ in range(3):
+ task, _ = adapter._prepare_task({"tenant": "dev", "message": dict(first)}, "peer-x", agent=agent)
+ assert task["status"]["state"] == protocol.STATE_COMPLETED
+ assert len({seen[0], *seen[2:]}) == 1
+ log = protocol.load_conversation("ctx-evict", limit=0)
+ assert [entry["role"] for entry in log].count("user") == 1
+ # The resends never spent the context's turn budget: the next distinct message is turn 2.
+ assert adapter._turns.track("ctx-evict") == 2
diff --git a/tests/plugins/test_a2a_plugin.py b/tests/plugins/test_a2a_plugin.py
index fabb89851da..6c01c22c307 100644
--- a/tests/plugins/test_a2a_plugin.py
+++ b/tests/plugins/test_a2a_plugin.py
@@ -1437,7 +1437,7 @@ class TestMultiAgentRouting:
monkeypatch.setenv("A2A_MAX_PINGPONG_TURNS", "2")
persisted = []
- monkeypatch.setattr(protocol, "persist_message", lambda context_id, role, text, task_id="": persisted.append(role))
+ monkeypatch.setattr(protocol, "persist_message", lambda context_id, role, text, task_id="", input_id="": persisted.append(role))
adapter = A2AAdapter(PlatformConfig(enabled=True, extra={
"agents": {"dev": {"profile": "dev", "tenant": "dev"}}
}))