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(skill): keep state file locking off async event loop

hubend83355847f1d
diff --git a/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py b/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py
index 8c0c449025..4bce801b6e 100644
--- a/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py
@@ -1,7 +1,6 @@
"""面向 agent 的 skill 管理工具封装。"""
from __future__ import annotations
-from jiuwenswarm.edition import is_enterprise
import asyncio
import logging
@@ -11,6 +10,7 @@ from typing import Any, Callable
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
+from jiuwenswarm.edition import is_enterprise
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager, SkillNameConflictError
from jiuwenswarm.server.runtime.skill.skill_prebuilt import is_skill_prebuilt_tenant
@@ -630,7 +630,8 @@ class SkillToolkit:
record_origin = str(target or "").strip() or resolved_source
meta = self._get_skill_meta(name) or {}
try:
- self._manager.record_skill_installation(
+ await asyncio.to_thread(
+ self._manager.record_skill_installation,
name=name,
source_type="user",
source=resolved_source,
diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.py
index b50576a29c..5e6fccf5ea 100644
--- a/jiuwenswarm/server/runtime/skill/skill_manager.py
+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py
@@ -471,27 +471,24 @@ def _handle_copy_error(exc: OSError, dest: Path, logger_prefix: str, src: Path |
def _state_transactional(method: Callable[..., Any]) -> Callable[..., Any]:
- """Wrap a SkillManager state-mutating method in the workspace lock.
+ """Wrap a synchronous SkillManager mutation in the workspace lock.
The outer-most wrapper reloads the authoritative skills_state.json from
disk before the body runs, so cross-pod AgentServer instances sharing one
workspace never overwrite each other's writes (last-writer-wins bug for
enterprise skill state). Nested wrappers reuse the same transaction and do
- not reload, preserving inner helper mutations.
+ not reload, preserving inner helper mutations. Async handlers must call a
+ decorated synchronous helper through ``asyncio.to_thread`` so waiting for
+ the cross-process file lock never blocks the event-loop thread.
"""
-
- @wraps(method)
- async def async_wrapper(self: "SkillManager", *args: Any, **kwargs: Any) -> Any:
- with self.state_transaction():
- return await method(self, *args, **kwargs)
+ if asyncio.iscoroutinefunction(method):
+ raise TypeError("_state_transactional only supports synchronous methods")
@wraps(method)
def sync_wrapper(self: "SkillManager", *args: Any, **kwargs: Any) -> Any:
with self.state_transaction():
return method(self, *args, **kwargs)
- if asyncio.iscoroutinefunction(method):
- return async_wrapper
return sync_wrapper
@@ -768,7 +765,7 @@ class SkillManager:
await self._sync_marketplace_repos()
# 每次列举前,把手动拷入 skills 目录、尚未登记的本地技能补登记为 local,
# 使其无需重启 server、刷新"我的技能"即可显示(与导入本地技能一致)。
- self._register_unmanaged_local_skills()
+ await asyncio.to_thread(self._register_unmanaged_local_skills)
local = self._scan_local_skills()
# 内置技能(仓内内置)两版都扫描展示;企业版不再跳过 builtin。
builtin = self._scan_builtin_skills()
@@ -958,7 +955,6 @@ class SkillManager:
raise ValueError(f"未找到 skill: {name}")
- @_state_transactional
async def handle_skills_toggle(self, params: dict) -> dict:
"""切换已安装本地 skill 的 enabled 状态。
@@ -968,6 +964,11 @@ class SkillManager:
记录,避免重名技能误操作另一条。
enabled: 目标状态
"""
+ return await asyncio.to_thread(self._handle_skills_toggle_sync, params)
+
+ @_state_transactional
+ def _handle_skills_toggle_sync(self, params: dict) -> dict:
+ """Apply one toggle while holding the workspace state transaction."""
name = params.get("name", "")
origin = str(params.get("origin", "") or "").strip() or None
enabled = params.get("enabled")
@@ -2506,7 +2507,8 @@ class SkillManager:
or descriptor.metadata.get("version")
or version_id
).strip()
- record = self._commit_source_skill_entity(
+ record = await asyncio.to_thread(
+ self._commit_source_skill_entity,
skill_dir,
skill_name=skill_name,
source_id=source_id,
@@ -2585,7 +2587,8 @@ class SkillManager:
or descriptor_metadata.get("owner_display_name")
or market_author
).strip()[:200]
- record = self._commit_source_skill_entity(
+ record = await asyncio.to_thread(
+ self._commit_source_skill_entity,
skill_dir,
skill_name=skill_name,
source_id=source_id,
@@ -2766,7 +2769,10 @@ class SkillManager:
"checked_at": checked_at,
}
)
- self._commit_skill_update_statuses(pending_updates)
+ await asyncio.to_thread(
+ self._commit_skill_update_statuses,
+ pending_updates,
+ )
return {"success": True, "items": items, "count": len(items)}
async def handle_skills_team_skills_hub_info(self, params: dict) -> dict:
@@ -3387,7 +3393,6 @@ class SkillManager:
protected_source_types=protected_source_types,
)
- @_state_transactional
async def handle_skills_uninstall(self, params: dict) -> dict:
"""卸载已安装的 skill.
@@ -3396,6 +3401,11 @@ class SkillManager:
origin: 可选,技能来源标识(如 ``clawhub:owner/slug``、URL)。提供时按
origin 精确定位目录与记录,避免重名技能误删另一个。
"""
+ return await asyncio.to_thread(self._handle_skills_uninstall_sync, params)
+
+ @_state_transactional
+ def _handle_skills_uninstall_sync(self, params: dict) -> dict:
+ """Uninstall one skill while holding the workspace state transaction."""
raw_name = params.get("name", "")
raw_origin = str(params.get("origin", "") or "").strip()
if not raw_name:
@@ -3811,7 +3821,8 @@ class SkillManager:
}
skill_version = str(meta.get("version") or "").strip() or None
- return self._commit_web_skill_install(
+ return await asyncio.to_thread(
+ self._commit_web_skill_install,
skill_dir,
skill_name=skill_name,
skill_version=skill_version,
diff --git a/jiuwenswarm/server/runtime/skill/skill_prebuilt.py b/jiuwenswarm/server/runtime/skill/skill_prebuilt.py
index 110dc1c378..9c130fed3f 100644
--- a/jiuwenswarm/server/runtime/skill/skill_prebuilt.py
+++ b/jiuwenswarm/server/runtime/skill/skill_prebuilt.py
@@ -440,7 +440,8 @@ class SkillPrebuiltSynchronizer:
if name in kept_prebuilt_names:
continue
try:
- removed = self._manager.remove_skill_installation_entity(
+ removed = await asyncio.to_thread(
+ self._manager.remove_skill_installation_entity,
name=name,
origin=str(row.get("origin") or "") or None,
expected_source_type=SOURCE_PREBUILT,
@@ -585,7 +586,8 @@ class SkillPrebuiltSynchronizer:
else item.package_url
)
try:
- row = self._manager.record_skill_installation(
+ row = await asyncio.to_thread(
+ self._manager.record_skill_installation,
name=installed_dir,
source_type=SOURCE_PREBUILT,
source=item.source_id or "enterprise-prebuilt",
diff --git a/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py b/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py
index a2d594f8c9..6520297d9f 100644
--- a/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py
+++ b/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py
@@ -3,8 +3,11 @@ from __future__ import annotations
import asyncio
import io
import json
+import threading
import zipfile
+from contextlib import contextmanager
from pathlib import Path
+from typing import Iterator
import pytest
@@ -407,3 +410,49 @@ def test_stale_prebuilt_removal_does_not_delete_same_name_user_skill(
assert skill_dir.is_dir()
assert manager.list_skill_installations() == [user_record]
assert result.succeeded == []
+
+
+def test_async_skill_handler_acquires_state_lock_off_event_loop(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workspace = tmp_path / "tenant"
+ builtin_dir = tmp_path / "builtin"
+ builtin_dir.mkdir()
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.skill.skill_manager.is_enterprise",
+ lambda: True,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.skill.skill_manager.get_builtin_skills_dir",
+ lambda: builtin_dir,
+ )
+ manager = SkillManager(workspace_dir=str(workspace))
+ _write_skill(workspace, "user-skill")
+ manager.record_skill_installation(
+ name="user-skill",
+ source_type="user",
+ )
+ original_transaction = manager.state_transaction
+ lock_threads: list[int] = []
+
+ @contextmanager
+ def observed_transaction() -> Iterator[None]:
+ lock_threads.append(threading.get_ident())
+ with original_transaction():
+ yield
+
+ monkeypatch.setattr(manager, "state_transaction", observed_transaction)
+ event_loop_thread = threading.get_ident()
+
+ async def exercise_handlers() -> dict:
+ await manager.handle_skills_list({})
+ return await manager.handle_skills_toggle(
+ {"name": "user-skill", "enabled": False}
+ )
+
+ result = asyncio.run(exercise_handlers())
+
+ assert result["success"] is True
+ assert len(lock_threads) >= 2
+ assert all(thread_id != event_loop_thread for thread_id in lock_threads)