Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(a2a): address batch7 review findings on shutdown, search, and credentials

NickFuryXXX7c0d35e6bc8e
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
index 1a111d4307..0ab748e77b 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
@@ -223,7 +223,12 @@ class A2AOutboundDispatcher:
items = [item for _, item in matches[:normalized_limit]]
return {
"items": items,
- "total": len(matches),
+ # Back-compat: "total" keeps its pre-existing meaning of "count of
+ # returned items". The full (unsliced) candidate count that used to
+ # live here is now reported separately as "total_matches" so
+ # existing consumers relying on total == len(items) don't break.
+ "total": len(items),
+ "total_matches": len(matches),
"matched_total": sum(1 for score, _ in matches if score > 0),
}
@@ -679,9 +684,25 @@ class A2AOutboundDispatcher:
card: dict[str, Any], credential: str
) -> tuple[dict[str, str], dict[str, str], dict[str, str]]:
"""Build credential placement from the Agent Card security contract."""
- requirements = card.get("securityRequirements") or []
- if not requirements or not credential:
+ if not credential:
return {}, {}, {}
+ requirements = card.get("securityRequirements") or []
+ if not requirements:
+ # Card doesn't declare a security contract (common for agents registered
+ # before A2A security schemes were adopted). Fall back to the previous
+ # unconditional bearer-header behavior instead of silently dropping a
+ # configured credential, which would turn into a remote 401.
+ return (
+ {
+ "Authorization": (
+ credential
+ if credential.lower().startswith("bearer ")
+ else f"Bearer {credential}"
+ )
+ },
+ {},
+ {},
+ )
schemes = card.get("securitySchemes") or {}
for requirement in requirements:
if not isinstance(requirement, dict):
@@ -976,6 +997,11 @@ class A2AOutboundDispatcher:
A2AOutboundDispatchStatus.WORKING,
A2AOutboundDispatchStatus.COMPLETED,
}
+ # Breaking change vs. earlier batches: remote_task_id/remote_context_id are
+ # intentionally NOT exposed here (still retained on the internal dataclass and
+ # persisted record). Callers must use the local dispatch_id for all follow-up
+ # a2a_get_dispatch/a2a_cancel_dispatch calls, so leaking the remote agent's own
+ # task/context identifiers would only invite an LLM caller to misuse them.
payload: dict[str, Any] = {
"ok": ok,
"dispatch_id": dispatch.dispatch_id,
diff --git a/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py b/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py
index 76b1120185..0cf6456076 100644
--- a/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py
@@ -480,7 +480,11 @@ class A2AChannel(BaseChannel):
)
self._uvicorn_server = uvicorn.Server(uv_cfg)
self._stopping = False
- listen_socket = self._bind_listen_socket(self.config.host, self.config.port)
+ # getaddrinfo() (DNS resolution) inside _bind_listen_socket is blocking;
+ # run it off the event loop so a slow lookup doesn't stall other coroutines.
+ listen_socket = await asyncio.to_thread(
+ self._bind_listen_socket, self.config.host, self.config.port
+ )
self._listen_socket = listen_socket
server_task = asyncio.create_task(
self._uvicorn_server.serve(sockets=[listen_socket]),
@@ -523,14 +527,24 @@ class A2AChannel(BaseChannel):
self._stopping = True
self._running = False
try:
- for request_id in list(self._pending):
- try:
- await self.cancel_pending_request(request_id)
- except Exception: # noqa: BLE001
- logger.exception(
- "[A2AChannel] failed to cancel downstream request during shutdown: %s",
- request_id,
- )
+ pending_ids = list(self._pending)
+ if pending_ids:
+ # Cancel concurrently: sequential awaits could each block up to the
+ # per-request ack timeout, making stop() take up to N x timeout.
+ results = await asyncio.gather(
+ *(
+ self.cancel_pending_request(request_id)
+ for request_id in pending_ids
+ ),
+ return_exceptions=True,
+ )
+ for request_id, result in zip(pending_ids, results):
+ if isinstance(result, Exception):
+ logger.error(
+ "[A2AChannel] failed to cancel downstream request during shutdown: %s",
+ request_id,
+ exc_info=result,
+ )
self._pending.clear()
if self._uvicorn_server is not None:
self._uvicorn_server.should_exit = True
diff --git a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py
index a936e3689e..0ddbff42e5 100644
--- a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py
+++ b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py
@@ -245,7 +245,8 @@ async def test_find_agents_returns_only_callable_minimal_catalog() -> None:
)
assert [item["agent_id"] for item in result["items"]] == ["agent-1"]
- assert result["total"] == 2
+ assert result["total"] == 1
+ assert result["total_matches"] == 2
assert result["matched_total"] == 2
assert "url" not in result["items"][0]
assert "credential_ref" not in result["items"][0]
@@ -266,12 +267,14 @@ async def test_find_agents_natural_language_ranks_without_hiding_catalog() -> No
"weather-agent",
}
assert generic["total"] == 2
+ assert generic["total_matches"] == 2
assert generic["matched_total"] == 0
weather = await dispatcher.find_agents(query="请帮我查询天气", limit=5)
assert weather["items"][0]["agent_id"] == "weather-agent"
assert weather["total"] == 2
+ assert weather["total_matches"] == 2
assert weather["matched_total"] == 1
strict = await dispatcher.find_agents(
@@ -730,6 +733,19 @@ def test_empty_security_requirement_allows_anonymous_access():
assert A2AOutboundDispatcher._credential_transport_options(card, "") == ({}, {}, {})
+def test_card_without_security_contract_still_sends_configured_credential():
+ """Regression: a card without securityRequirements must not silently drop a
+ configured credential_ref (previously fell back to a bearer header)."""
+ card = {"securitySchemes": {}}
+
+ assert A2AOutboundDispatcher._credential_required(card) is False
+ assert A2AOutboundDispatcher._credential_transport_options(card, "secret") == (
+ {"Authorization": "Bearer secret"},
+ {},
+ {},
+ )
+
+
@pytest.mark.asyncio
async def test_cancellation_moves_record_out_of_processing_and_reraises() -> None:
client = _FakeClient(