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
加固同轮技能刷新push的并发安全(PR 9121 检视意见)
yt20266999fbf5620a
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 90e59d908f..fa507d8139 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -2677,6 +2677,10 @@ class JiuWenSwarmDeepAdapter:self._disabled_tools_rail: DisabledToolsRail | None = Noneself._skill_rail: SkillUseRail | None = Noneself._enabled_skills: list[str] | None = None+ # 串行化 refresh_enabled_skills_from_db 的整段执行(DB 读 → enabled 写 →+ # rail 换装):同轮 push、轮边界刷新与会话内安装回调可能并发进入同一+ # adapter,换装段 unregister→register→赋值间有 await 挂起点。+ self._skill_refresh_lock = asyncio.Lock()self._skill_authorization_rail: Any = None# 企业预置 Skill 名快照(安装账本 source_type=prebuilt),供动态授权# trust 判定使用;由白名单同步/热刷新/_refresh_skill_identity 维护。@@ -3399,6 +3403,8 @@ class JiuWenSwarmDeepAdapter:back to the lazy next-turn semantics (a failed refresh records theshared 30s retry-suppression stamp, so the immediately followingboundary retry may be suppressed) and other sessions are untouched.+ A session cleaned up while this push waits on the lock has its+ orphaned lock entry dropped so ``has_session_runtime`` stays truthful."""session_id = str(getattr(request, "session_id", None) or "").strip()if not session_id:@@ -3410,11 +3416,18 @@ class JiuWenSwarmDeepAdapter:returnlock = self._session_adapter_locks.setdefault(sid, asyncio.Lock())try:+ adapter = Noneasync with lock:adapter = self._session_adapters.get(sid)- if adapter is None:- return- await self._refresh_session_skills_if_stale(sid, adapter)+ if adapter is not None:+ await self._refresh_session_skills_if_stale(sid, adapter)+ if adapter is None:+ # The session was cleaned up while this push waited on the lock;+ # drop the orphaned lock entry (same idle discipline as+ # ``cleanup_session_adapter``) so ``has_session_runtime`` stops+ # reporting runtime for a session that no longer exists.+ if self._is_session_lock_idle(sid, lock):+ self._session_adapter_locks.pop(sid, None)except Exception as exc: # noqa: BLE001 — push 失败回退下一轮 lazy 追平logger.warning("[JiuWenSwarmDeepAdapter] same-turn skill refresh push failed "@@ -9541,7 +9554,15 @@ class JiuWenSwarmDeepAdapter:"[JiuWenSwarmDeepAdapter] refresh_enabled_skills_from_db skipped: instance not ready")return False-+ # 整段持锁串行(DB 读 → enabled 写 → rail 换装):同轮 push(持 root+ # 会话锁)、轮边界刷新与会话内 ``_on_installed_skills_changed`` 回调可能+ # 并发到达同一 adapter,换装段 unregister→register→赋值间有 await 挂起点,+ # 交错执行会挂上两个 rail 并让 ``_skill_rail`` 指向陈旧实例。+ async with self._skill_refresh_lock:+ return await self._refresh_enabled_skills_from_db_locked()++ async def _refresh_enabled_skills_from_db_locked(self) -> bool:+ """``refresh_enabled_skills_from_db`` 的持锁执行体(入口已持 ``_skill_refresh_lock``)。"""try:manager = self._skill_manager or SkillManager(workspace_dir=self._workspace_dir,diff --git a/tests/unit_tests/agentserver/test_skill_session_lazy_refresh.py b/tests/unit_tests/agentserver/test_skill_session_lazy_refresh.pyindex 18c480aaa0..f50bef2174 100644--- a/tests/unit_tests/agentserver/test_skill_session_lazy_refresh.py+++ b/tests/unit_tests/agentserver/test_skill_session_lazy_refresh.py@@ -188,6 +188,8 @@ async def test_push_refreshes_bound_session_same_turn(assert child_refreshed is True# Same lazy bookkeeping path: stamped current at the root stamp (2).assert root._session_skill_versions.get("sess_a") == 2+ # Live session: the lock entry stays for subsequent turns.+ assert "sess_a" in root._session_adapter_locks@pytest.mark.asyncio@@ -333,3 +335,44 @@ async def test_push_survives_adapter_evicted_while_waiting_on_lock(# No refresh was even attempted: no version stamp, no failure stamp.assert root._session_skill_versions == {}assert root._session_skill_refresh_failures == {}+ # The orphaned lock entry is dropped: has_session_runtime must not keep+ # reporting runtime for a session cleaned up while the push waited.+ assert "sess_a" not in root._session_adapter_locks+++async def test_refresh_enabled_skills_from_db_serializes_concurrent_swaps(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Concurrent refresh entry points must not interleave the rail swap.++ The push path (root session lock held), the turn-boundary refresh and the+ in-session ``_on_installed_skills_changed`` callback can all call+ ``refresh_enabled_skills_from_db`` on one adapter concurrently; the swap+ section has await points, so the public entry serializes the whole body.+ """+ root = _make_push_root(_instance=object(), _skill_refresh_lock=asyncio.Lock())+ monkeypatch.setattr(interface_deep_module, "is_skill_prebuilt_tenant", lambda *_a, **_k: True)++ in_flight = 0+ max_in_flight = 0++ async def _locked_body() -> bool:+ nonlocal in_flight, max_in_flight+ in_flight += 1+ max_in_flight = max(max_in_flight, in_flight)+ try:+ await asyncio.sleep(0) # yield so the peer task can queue on the lock+ return True+ finally:+ in_flight -= 1++ root._refresh_enabled_skills_from_db_locked = _locked_body # type: ignore[method-assign]++ results = await asyncio.gather(+ root.refresh_enabled_skills_from_db(),+ root.refresh_enabled_skills_from_db(),+ )++ assert results == [True, True]+ assert max_in_flight == 1