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

解决企业Gateway对已删除AgentServer Pod无限重连events/stream 的问题

meizi6051910f8db89
diff --git a/jiuwenswarm/gateway/routing/http_agent_client.py b/jiuwenswarm/gateway/routing/http_agent_client.py
index 61c4ab95bf..213ca25d7b 100644
--- a/jiuwenswarm/gateway/routing/http_agent_client.py
+++ b/jiuwenswarm/gateway/routing/http_agent_client.py
@@ -35,6 +35,8 @@ logger = logging.getLogger(__name__)
_CONNECT_TIMEOUT_SECONDS = 10.0
_PUSH_RETRY_SECONDS = 3.0
+# 企业按 Pod 订阅:连续 TCP 失败才停,避免活 Pod 闪断被立刻 drop。
+_PUSH_MAX_CONNECT_FAILURES = 3
# 与 WebSocketAgentServerClient._delayed_cleanup_cancelled_request_id 对齐。
_CANCELLED_RID_TTL_SECONDS = 2.0
@@ -142,6 +144,7 @@ class HttpSseAgentServerClient(AgentServerClient):
timeout_s: float = AGENT_REQUEST_TIMEOUT_SECONDS,
http_client: httpx.AsyncClient | None = None,
link_mtls_config: LinkMTLSConfig | None = None,
+ retry_push_connect: bool = True,
) -> None:
self._timeout_s = float(timeout_s)
self._http = http_client
@@ -158,6 +161,9 @@ class HttpSseAgentServerClient(AgentServerClient):
self._cancelled_request_ids: set[str] = set()
self._inflight_stream_ids: dict[str, _StreamScope | None] = {}
self._link_mtls = link_mtls_config
+ # False:连续 TCP 失败后停(企业按 Pod IP)。True:继续重连(开源固定 URL)。
+ self._retry_push_connect = retry_push_connect
+ self._push_connect_failures = 0
def _link_config(self) -> LinkMTLSConfig:
if self._link_mtls is None:
@@ -181,7 +187,21 @@ class HttpSseAgentServerClient(AgentServerClient):
self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None
) -> None:
self._on_server_push = handler
- if handler is not None and self._running and self._push_task is None:
+ self._start_push_loop()
+
+ def add_push_done_callback(
+ self, callback: Callable[[asyncio.Task[None]], None]
+ ) -> None:
+ """Observe push-loop exit without poking ``_push_task``."""
+ task = self._push_task
+ if isinstance(task, asyncio.Task):
+ task.add_done_callback(callback)
+
+ def _start_push_loop(self) -> None:
+ task = self._push_task
+ if task is not None and task.done():
+ self._push_task = None
+ if self._on_server_push is not None and self._running and self._push_task is None:
self._push_task = asyncio.create_task(self._push_loop(), name="agent-http-push")
@property
@@ -260,9 +280,9 @@ class HttpSseAgentServerClient(AgentServerClient):
)
self._server_ready = True
self._running = True
+ self._push_connect_failures = 0
logger.info("[HttpSseAgentServerClient] health ok: %s", health_url)
- if self._on_server_push is not None and self._push_task is None:
- self._push_task = asyncio.create_task(self._push_loop(), name="agent-http-push")
+ self._start_push_loop()
async def disconnect(self) -> None:
self._running = False
@@ -471,6 +491,7 @@ class HttpSseAgentServerClient(AgentServerClient):
),
timeout=timeout,
) as response:
+ self._push_connect_failures = 0
response.raise_for_status()
async for frame in iter_sse_data_frames(response):
if frame.get("event_type") == "gateway.push_ready":
@@ -500,6 +521,21 @@ class HttpSseAgentServerClient(AgentServerClient):
except Exception as exc: # noqa: BLE001
if not self._running:
return
+ if not self._retry_push_connect and isinstance(
+ exc, (httpx.ConnectError, httpx.ConnectTimeout)
+ ):
+ self._push_connect_failures += 1
+ if self._push_connect_failures >= _PUSH_MAX_CONNECT_FAILURES:
+ logger.warning(
+ "[HttpSseAgentServerClient] events/stream 目标不可达,停止推送循环: "
+ "%s url=%s failures=%s",
+ exc,
+ url,
+ self._push_connect_failures,
+ )
+ self._running = False
+ self._server_ready = False
+ return
logger.warning(
"[HttpSseAgentServerClient] events/stream 断开,%.0fs 后重连: %s",
_PUSH_RETRY_SECONDS,
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py
index 887fa67554..15c27d4e0b 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py
@@ -188,6 +188,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):
self._pod_clients: dict[str, HttpSseAgentServerClient] = {}
self._pod_connect_lock = asyncio.Lock()
self._rpc_origins: dict[tuple[str, str], str] = {}
+ self._drop_tasks: set[asyncio.Task[None]] = set()
def set_server_push_handler(
self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None
@@ -217,11 +218,16 @@ class RuntimeRoutedAgentClient(AgentServerClient):
async def _ensure_pod_push(self, base_url: str) -> None:
if self._on_server_push is None:
return
+ stale: HttpSseAgentServerClient | None = None
async with self._pod_connect_lock:
self._ensure_connected()
client = self._pod_clients.get(base_url)
+ # Fallback if push-done drop hasn't run yet (same IP reused).
+ if client is not None and not getattr(client, "_running", True):
+ stale = self._pod_clients.pop(base_url)
+ client = None
if client is None:
- client = HttpSseAgentServerClient()
+ client = HttpSseAgentServerClient(retry_push_connect=False)
client.set_server_push_handler(
lambda wire: self._handle_pod_push(base_url, wire)
)
@@ -232,8 +238,57 @@ class RuntimeRoutedAgentClient(AgentServerClient):
await client.disconnect()
raise
self._pod_clients[base_url] = client
+ client.add_push_done_callback(
+ lambda _task, url=base_url, bound=client: self._schedule_drop_pod_client(
+ url, bound
+ )
+ )
+ if stale is not None:
+ try:
+ await stale.disconnect()
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[RuntimeRouted] 断开旧 Pod 推送客户端失败: %s (%s)",
+ base_url,
+ exc,
+ )
await client.wait_push_ready()
+ def _schedule_drop_pod_client(
+ self, base_url: str, client: HttpSseAgentServerClient
+ ) -> None:
+ if not self._connected:
+ return
+ try:
+ task = asyncio.get_running_loop().create_task(
+ self._drop_pod_client(base_url, client),
+ name="runtime-drop-pod-push",
+ )
+ except RuntimeError:
+ return
+ self._drop_tasks.add(task)
+ task.add_done_callback(self._drop_tasks.discard)
+
+ async def _drop_pod_client(
+ self, base_url: str, client: HttpSseAgentServerClient
+ ) -> None:
+ async with self._pod_connect_lock:
+ if self._pod_clients.get(base_url) is not client:
+ return
+ self._pod_clients.pop(base_url, None)
+ logger.warning(
+ "[RuntimeRouted] 推送循环已结束,丢弃客户端: %s",
+ base_url,
+ )
+ try:
+ await client.disconnect()
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[RuntimeRouted] 断开旧 Pod 推送客户端失败: %s (%s)",
+ base_url,
+ exc,
+ )
+
async def connect(self, uri: str) -> None:
_ = uri
self._connected = True
@@ -248,6 +303,10 @@ class RuntimeRoutedAgentClient(AgentServerClient):
async with self._pod_connect_lock:
clients = list(self._pod_clients.values())
self._pod_clients.clear()
+ drop_tasks = list(self._drop_tasks)
+ self._drop_tasks.clear()
+ if drop_tasks:
+ await asyncio.gather(*drop_tasks, return_exceptions=True)
results = await asyncio.gather(
*(client.disconnect() for client in clients),
return_exceptions=True,
diff --git a/tests/unit_tests/gateway/test_http_agent_client.py b/tests/unit_tests/gateway/test_http_agent_client.py
index c5fc8d5041..b37295cb88 100644
--- a/tests/unit_tests/gateway/test_http_agent_client.py
+++ b/tests/unit_tests/gateway/test_http_agent_client.py
@@ -863,6 +863,172 @@ async def test_push_loop_backs_off_after_clean_stream_end(monkeypatch):
await server.wait_closed()
+async def test_push_loop_stops_when_ephemeral_pod_is_unreachable(monkeypatch):
+ """Deleted Pod IPs must not retry events/stream forever."""
+ import jiuwenswarm.gateway.routing.http_agent_client as hac
+
+ monkeypatch.setattr(hac, "_PUSH_RETRY_SECONDS", 0.05)
+ monkeypatch.setattr(hac, "_CONNECT_TIMEOUT_SECONDS", 0.3)
+
+ stream_hits = 0
+ hold = asyncio.Event()
+
+ async def on_push(_frame: dict) -> None:
+ return None
+
+ async def _handle(
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter
+ ) -> None:
+ nonlocal stream_hits
+ try:
+ header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)
+ request_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")
+ _method, path, *_rest = request_line.split(" ")
+ if path.endswith("/health"):
+ writer.write(_http_json({"ok": True, "data": {"status": "ready"}}))
+ await writer.drain()
+ return
+ if path.endswith("/events/stream"):
+ stream_hits += 1
+ writer.write(
+ b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"
+ b"Cache-Control: no-cache\r\nConnection: keep-alive\r\n\r\n"
+ )
+ await writer.drain()
+ await hold.wait()
+ return
+ writer.write(_http_json({"ok": False, "error": {"code": "NOT_FOUND"}}))
+ await writer.drain()
+ finally:
+ writer.close()
+ try:
+ await writer.wait_closed()
+ except Exception: # noqa: BLE001
+ pass
+
+ server = await asyncio.start_server(_handle, "127.0.0.1", 0)
+ port = server.sockets[0].getsockname()[1]
+ client = HttpSseAgentServerClient(retry_push_connect=False)
+ client.set_server_push_handler(on_push)
+ try:
+ await client.connect(f"http://127.0.0.1:{port}")
+ await asyncio.sleep(0.05)
+ assert stream_hits == 1
+ assert client._running is True
+ server.close()
+ await server.wait_closed()
+ hold.set()
+ async with asyncio.timeout(3):
+ while client._running:
+ await asyncio.sleep(0.05)
+ hits_after = stream_hits
+ await asyncio.sleep(0.25)
+ assert stream_hits == hits_after
+ finally:
+ hold.set()
+ await client.disconnect()
+
+
+async def test_ephemeral_push_resets_connect_failures_after_success(monkeypatch):
+ """N=3: two TCP fails keep running; a successful stream zeros the counter; three in a row stop."""
+ import jiuwenswarm.gateway.routing.http_agent_client as hac
+
+ monkeypatch.setattr(hac, "_PUSH_RETRY_SECONDS", 0.02)
+ monkeypatch.setattr(hac, "_PUSH_MAX_CONNECT_FAILURES", 3)
+
+ script: asyncio.Queue[str] = asyncio.Queue()
+ holds: list[asyncio.Event] = []
+
+ class _HoldStream(httpx.AsyncByteStream):
+ def __init__(self, hold: asyncio.Event) -> None:
+ self._hold = hold
+
+ async def __aiter__(self):
+ yield b'data: {"event_type": "gateway.push_ready"}\n\n'
+ await self._hold.wait()
+
+ async def aclose(self) -> None:
+ self._hold.set()
+
+ class _ScriptedTransport(httpx.AsyncBaseTransport):
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ if path.endswith("/health"):
+ return httpx.Response(
+ 200,
+ json={"ok": True, "data": {"status": "ready"}},
+ request=request,
+ )
+ if not path.endswith("/events/stream"):
+ return httpx.Response(404, request=request)
+ action = await script.get()
+ if action == "fail":
+ raise httpx.ConnectError(
+ "All connection attempts failed",
+ request=request,
+ )
+ hold = asyncio.Event()
+ holds.append(hold)
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=_HoldStream(hold),
+ request=request,
+ )
+
+ async def _wait_failures(count: int) -> None:
+ async with asyncio.timeout(2):
+ while client._push_connect_failures != count:
+ await asyncio.sleep(0)
+
+ http = httpx.AsyncClient(transport=_ScriptedTransport())
+ client = HttpSseAgentServerClient(http_client=http, retry_push_connect=False)
+
+ async def on_push(_frame: dict) -> None:
+ return None
+
+ client.set_server_push_handler(on_push)
+ try:
+ await client.connect("http://10.244.0.190:8766")
+ assert client._running is True
+ assert client._push_connect_failures == 0
+
+ await script.put("fail")
+ await _wait_failures(1)
+ assert client._running is True
+
+ await script.put("fail")
+ await _wait_failures(2)
+ assert client._running is True
+
+ await script.put("ok")
+ async with asyncio.timeout(2):
+ while client._push_connect_failures != 0 or not client._push_ready.is_set():
+ await asyncio.sleep(0)
+ assert client._running is True
+ assert len(holds) == 1
+
+ holds[-1].set()
+ await asyncio.sleep(0.05)
+ assert client._running is True
+ assert client._push_connect_failures == 0
+
+ await script.put("fail")
+ await script.put("fail")
+ await script.put("fail")
+ async with asyncio.timeout(2):
+ while client._running:
+ await asyncio.sleep(0)
+ assert client._push_connect_failures == 3
+ finally:
+ for hold in holds:
+ hold.set()
+ await client.disconnect()
+ await http.aclose()
+
+
@pytest.mark.asyncio
async def test_send_request_with_base_url_skips_connect():
seen: list[str] = []
diff --git a/tests/unit_tests/gateway/test_runtime_routed_client.py b/tests/unit_tests/gateway/test_runtime_routed_client.py
index 01297c684b..067bf04b02 100644
--- a/tests/unit_tests/gateway/test_runtime_routed_client.py
+++ b/tests/unit_tests/gateway/test_runtime_routed_client.py
@@ -248,7 +248,8 @@ async def test_concurrent_pod_subscription_and_failed_registration_cleanup(monke
created = []
class PodClient:
- def __init__(self):
+ def __init__(self, *, retry_push_connect: bool = True, **_kwargs):
+ assert retry_push_connect is False
created.append(self)
self.closed = False
self.fail = False
@@ -256,6 +257,9 @@ async def test_concurrent_pod_subscription_and_failed_registration_cleanup(monke
def set_server_push_handler(self, handler):
self.handler = handler
+ def add_push_done_callback(self, callback):
+ return None
+
async def connect(self, uri):
self.fail = "bad" in uri
await asyncio.sleep(0)
@@ -283,6 +287,133 @@ async def test_concurrent_pod_subscription_and_failed_registration_cleanup(monke
assert all(pod.closed for pod in created)
+async def test_unreachable_pod_push_client_is_replaced_on_next_ensure(monkeypatch):
+ created = []
+
+ class PodClient:
+ def __init__(self, *, retry_push_connect: bool = True, **_kwargs):
+ assert retry_push_connect is False
+ created.append(self)
+ self.closed = False
+ self._running = True
+
+ def set_server_push_handler(self, handler):
+ self.handler = handler
+
+ def add_push_done_callback(self, callback):
+ return None
+
+ async def connect(self, uri):
+ self.uri = uri
+
+ async def wait_push_ready(self):
+ return None
+
+ async def disconnect(self):
+ self.closed = True
+ self._running = False
+
+ monkeypatch.setattr(_routed_mod, "HttpSseAgentServerClient", PodClient)
+ client = RuntimeRoutedAgentClient(route_client=_FakeRoute(), http_client=_FakeHttp())
+ client.set_server_push_handler(lambda wire: asyncio.sleep(0))
+ await client.connect("unused")
+ dead = "http://10.244.0.190:8766"
+ live = "http://10.244.0.192:8766"
+ try:
+ await client._ensure_pod_push(dead)
+ assert dead in client._pod_clients
+ created[0]._running = False
+ await client._ensure_pod_push(dead)
+ assert created[0].closed is True
+ assert client._pod_clients[dead] is created[1]
+ await client._ensure_pod_push(live)
+ assert set(client._pod_clients) == {dead, live}
+ assert len(created) == 3
+ finally:
+ await client.disconnect()
+ assert all(pod.closed for pod in created)
+
+
+async def test_push_task_done_drops_pod_client_immediately(monkeypatch):
+ created = []
+
+ class PodClient:
+ def __init__(self, *, retry_push_connect: bool = True, **_kwargs):
+ assert retry_push_connect is False
+ created.append(self)
+ self.closed = False
+ self._running = True
+ self._push_task: asyncio.Task[None] | None = None
+ self._stop = asyncio.Event()
+ self._done_callbacks = []
+
+ def set_server_push_handler(self, handler):
+ self.handler = handler
+
+ def add_push_done_callback(self, callback):
+ task = self._push_task
+ if isinstance(task, asyncio.Task):
+ task.add_done_callback(callback)
+ return
+ self._done_callbacks.append(callback)
+
+ async def connect(self, uri):
+ self.uri = uri
+
+ async def _loop() -> None:
+ await self._stop.wait()
+
+ self._push_task = asyncio.create_task(_loop())
+ for callback in self._done_callbacks:
+ self._push_task.add_done_callback(callback)
+ self._done_callbacks.clear()
+
+ async def wait_push_ready(self):
+ return None
+
+ async def disconnect(self):
+ self.closed = True
+ self._running = False
+ self._stop.set()
+ task = self._push_task
+ if isinstance(task, asyncio.Task) and not task.done():
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception):
+ pass
+
+ async def simulate_unreachable(self):
+ self._running = False
+ self._stop.set()
+ task = self._push_task
+ if isinstance(task, asyncio.Task):
+ await asyncio.wait_for(asyncio.shield(task), timeout=2)
+
+ monkeypatch.setattr(_routed_mod, "HttpSseAgentServerClient", PodClient)
+ client = RuntimeRoutedAgentClient(route_client=_FakeRoute(), http_client=_FakeHttp())
+ client.set_server_push_handler(lambda wire: asyncio.sleep(0))
+ await client.connect("unused")
+ dead = "http://10.244.0.190:8766"
+ live = "http://10.244.0.192:8766"
+ try:
+ await client._ensure_pod_push(dead)
+ assert dead in client._pod_clients
+ await created[0].simulate_unreachable()
+ if client._drop_tasks:
+ await asyncio.gather(*list(client._drop_tasks), return_exceptions=True)
+ assert dead not in client._pod_clients
+ assert created[0].closed is True
+ await client._ensure_pod_push(live)
+ assert list(client._pod_clients) == [live]
+ assert len(created) == 2
+ finally:
+ await client.disconnect()
+ assert all(pod.closed for pod in created)
+
+
@pytest.mark.asyncio
async def test_reverse_rpc_reply_is_pinned_to_origin_pod():
from jiuwenswarm.common.e2a.adapters import build_acp_tool_response_message