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: <asyncio.locks.Lock object> is bound to a different event loop 问题修复
slichengsongf42fe4e8e031
diff --git a/jiuwenswarm/extensions/yuanrong_frontend_client.py b/jiuwenswarm/extensions/yuanrong_frontend_client.pyindex 9b2f36441c..b0fa9ae3fe 100644--- a/jiuwenswarm/extensions/yuanrong_frontend_client.py+++ b/jiuwenswarm/extensions/yuanrong_frontend_client.py@@ -65,6 +65,7 @@ class YuanrongFrontendAgentClient(AgentServerClient):invoke_timeout_s: float = 60.0,agent_timeout_s: float = 300.0,agent_namespace: str = "default",+ session_ttl_s: int = 900,) -> None:self._frontend_endpoint = (frontend_endpoint or "").rstrip("/")self._function_version_urn = (function_version_urn or "").strip()@@ -72,6 +73,9 @@ class YuanrongFrontendAgentClient(AgentServerClient):self._invoke_timeout_s = float(invoke_timeout_s)self._agent_timeout_s = float(agent_timeout_s)self._agent_namespace = str(agent_namespace or "default").strip() or "default"+ # yuanrong X-Instance-Session.sessionTTL,单位:秒;0 = 立即解绑。+ # 默认 900s(15 分钟),保证会话对实例的亲和性,避免每次调用重建实例。+ self._session_ttl_s = max(int(session_ttl_s), 0)self._connected = Falseself._server_ready = False@@ -472,7 +476,11 @@ class YuanrongFrontendAgentClient(AgentServerClient):headers = {"Content-Type": "application/json","X-Instance-Session": json.dumps(- {"sessionID": session_id, "concurrency": self._concurrency},+ {+ "sessionID": session_id,+ "sessionTTL": self._session_ttl_s,+ "concurrency": self._concurrency,+ },ensure_ascii=False,),}diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex d2c40326fc..4ede7ebec9 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -17,6 +17,7 @@ import osimport platformimport reimport subprocess+import threadingimport timefrom collections import Counterfrom contextvars import ContextVar, Token@@ -329,9 +330,59 @@ def get_runtime_tool_session_id() -> str | None:logger = logging.getLogger(__name__)-_PERSISTENT_CHECKPOINTER_LOCK = asyncio.Lock()+_PERSISTENT_CHECKPOINTER_LOCK: asyncio.Lock | None = None+_PERSISTENT_CHECKPOINTER_LOCK_LOOP: asyncio.AbstractEventLoop | None = None+_PERSISTENT_CHECKPOINTER_LOCK_INIT = threading.Lock()_PERSISTENT_CHECKPOINTER_READY = False++def _running_loop() -> asyncio.AbstractEventLoop | None:+ try:+ return asyncio.get_running_loop()+ except RuntimeError:+ return None+++async def _get_persistent_checkpointer_lock() -> asyncio.Lock:+ """Lazy-init or rebind the process-wide checkpointer lock to the running loop.++ ``asyncio.Lock`` binds to the loop of its first ``acquire()``; any later+ acquire from a different loop raises ``RuntimeError("... is bound to a+ different event loop")``. The first call may have happened on a transient+ loop (test harness, ephemeral worker) that is gone by the time AgentServer's+ main loop needs the lock. To stay correct under that drift we:++ 1. Lazily construct the Lock inside the caller's running loop (guarded by a+ ``threading.Lock`` so concurrent first-acquires from different threads+ cannot create two Locks).+ 2. Before returning, verify the Lock is still bound to the current loop. If+ it is bound to a dead/foreign loop, drop and rebuild it so the caller can+ re-acquire safely. This rebinding is also done under the threading guard.++ After ``_PERSISTENT_CHECKPOINTER_READY`` flips True no one acquires the lock,+ so rebinding is a no-op for the steady state.+ """+ global _PERSISTENT_CHECKPOINTER_LOCK, _PERSISTENT_CHECKPOINTER_LOCK_LOOP+ current = _running_loop()+ if current is None:+ raise RuntimeError(+ "_get_persistent_checkpointer_lock must be called from a running event loop"+ )+ with _PERSISTENT_CHECKPOINTER_LOCK_INIT:+ bound = _PERSISTENT_CHECKPOINTER_LOCK_LOOP+ if _PERSISTENT_CHECKPOINTER_LOCK is None or bound is None or bound is not current:+ if bound is not None and bound is not current and not bound.is_closed():+ logger.warning(+ "[JiuWenSwarmDeepAdapter] _PERSISTENT_CHECKPOINTER_LOCK rebound: "+ "old_loop=%r new_loop=%r (lock repr=%r)",+ bound,+ current,+ _PERSISTENT_CHECKPOINTER_LOCK,+ )+ _PERSISTENT_CHECKPOINTER_LOCK = asyncio.Lock()+ _PERSISTENT_CHECKPOINTER_LOCK_LOOP = current+ return _PERSISTENT_CHECKPOINTER_LOCK+_ACP_BLOCKED_DEFAULT_TOOL_NAMES = frozenset({"read_file",@@ -513,7 +564,21 @@ async def ensure_persistent_checkpointer() -> None:if _PERSISTENT_CHECKPOINTER_READY:return- async with _PERSISTENT_CHECKPOINTER_LOCK:+ lock = await _get_persistent_checkpointer_lock()+ acquired = False+ try:+ try:+ await lock.acquire()+ except RuntimeError as acquire_exc:+ logger.exception(+ "[JiuWenSwarmDeepAdapter] _PERSISTENT_CHECKPOINTER_LOCK acquire failed: %s "+ "(lock repr=%r, running_loop=%r)",+ acquire_exc,+ lock,+ asyncio.get_event_loop(),+ )+ raise+ acquired = Trueif _PERSISTENT_CHECKPOINTER_READY:return@@ -538,6 +603,9 @@ async def ensure_persistent_checkpointer() -> None:exc,)raise RuntimeError("persistent checkpointer initialization failed") from exc+ finally:+ if acquired:+ lock.release()_MODE_DISPLAY_MAP: dict[str, dict[str, str]] = {diff --git a/tests/unit_tests/extensions/test_yuanrong_frontend_client.py b/tests/unit_tests/extensions/test_yuanrong_frontend_client.pyindex fa5f3bf57c..2df8cd7260 100644--- a/tests/unit_tests/extensions/test_yuanrong_frontend_client.py+++ b/tests/unit_tests/extensions/test_yuanrong_frontend_client.py@@ -45,14 +45,14 @@ def test_invoke_headers_without_user_id(client: YuanrongFrontendAgentClientProbeassert "X-Session-Context" not in headersinstance = json.loads(headers["X-Instance-Session"])- assert instance == {"sessionID": "sess-1", "concurrency": 2}+ assert instance == {"sessionID": "sess-1", "sessionTTL": 900, "concurrency": 2}def test_invoke_headers_with_user_id(client: YuanrongFrontendAgentClientProbe):headers = client.invoke_headers("sess-1", user_id="alice")assert json.loads(headers["X-Session-Context"]) == {"sessionCtx": "alice"}- assert json.loads(headers["X-Instance-Session"]) == {"sessionID": "sess-1", "concurrency": 2}+ assert json.loads(headers["X-Instance-Session"]) == {"sessionID": "sess-1", "sessionTTL": 900, "concurrency": 2}def test_invoke_headers_stream_accepts_sse(client: YuanrongFrontendAgentClientProbe):