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_turbo): read_file 重试覆盖 success=False 结果模式,瞬时锁错误按退避序列重试
d30029696e5ef48ee753f
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_common.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_common.pyindex 91105aa4c8..87aa410273 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_common.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_common.py@@ -408,6 +408,67 @@ class PptCommon:return text[:max_chars] + "\n\n...(内容已截断)"return text+ _TRANSIENT_LOCK_ERROR_MARKERS: tuple[str, ...] = (+ "cannot operate on a closed database",+ "database is locked",+ "database table is locked",+ )+ # 退避间隔需覆盖秒级的陈旧锁存活期,立即重试大概率命中同一把坏锁+ _TRANSIENT_LOCK_RETRY_DELAYS: tuple[float, ...] = (0.5, 1.0, 2.0)++ @classmethod+ def _tool_result_failure_text(cls, result: Any) -> str:+ """从 read_file 工具结果中提取失败错误文本;成功结果返回空串。"""+ if hasattr(result, "success"):+ if result.success is False:+ if hasattr(result, "error") and result.error:+ return str(result.error)+ return str(result)+ return ""+ if isinstance(result, str):+ text = result.strip()+ return text if text.startswith(("success=False", "success= False")) else ""+ if isinstance(result, dict):+ if result.get("success") is False:+ error = result.get("error")+ return str(error) if error else str(result)+ return ""+ return ""++ @classmethod+ def _is_transient_lock_failure(cls, failure_text: str) -> bool:+ lowered = failure_text.lower()+ return any(marker in lowered for marker in cls._TRANSIENT_LOCK_ERROR_MARKERS)++ @classmethod+ async def _wait_for_transient_retry(+ cls,+ log_prefix: str,+ attempt: int,+ path: str,+ failure_text: str,+ ) -> bool:+ """瞬时锁错误按退避间隔等待重试;额度耗尽返回 False。"""+ if attempt > len(cls._TRANSIENT_LOCK_RETRY_DELAYS):+ logger.warning(+ "%s 读取文件瞬时锁错误(重试耗尽) path=%s: %s",+ log_prefix,+ path,+ failure_text,+ )+ return False+ delay = cls._TRANSIENT_LOCK_RETRY_DELAYS[attempt - 1]+ logger.warning(+ "%s 读取文件瞬时锁错误(第%d次),%.1fs后重试 path=%s: %s",+ log_prefix,+ attempt,+ delay,+ path,+ failure_text,+ )+ await asyncio.sleep(delay)+ return True+@classmethodasync def read_file_with_retry(cls,@@ -416,24 +477,28 @@ class PptCommon:*,log_prefix: str = "[ppt]",) -> str:- """读取文件内容;非 AbortError 异常时重试一次。"""+ """读取文件内容;瞬时锁错误(异常或失败结果)按退避序列重试,其他异常重试一次。"""if not path:return ""if not node.has_tool("read_file"):logger.warning("%s read_file 工具不可用 %s", log_prefix, path)return ""- for attempt in (1, 2):+ attempt = 0+ while True:+ attempt += 1try:result = await node.call_tool("read_file", file_path=path)- return cls.parse_tool_file_content(result)except Exception as e:if isinstance(e, AbortError):raise- if attempt < 2:+ if cls._is_transient_lock_failure(str(e)):+ if await cls._wait_for_transient_retry(log_prefix, attempt, path, str(e)):+ continue+ return ""+ if attempt == 1:logger.warning(- "%s 读取文件失败(第%d次),重试 path=%s: %s",+ "%s 读取文件失败(第1次),重试 path=%s: %s",log_prefix,- attempt,path,e,)@@ -445,7 +510,15 @@ class PptCommon:e,)return ""- return ""++ failure_text = cls._tool_result_failure_text(result)+ if failure_text and cls._is_transient_lock_failure(failure_text):+ if await cls._wait_for_transient_retry(+ log_prefix, attempt, path, failure_text+ ):+ continue+ return ""+ return cls.parse_tool_file_content(result)@classmethodasync def write_file(diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_read_file_with_retry.py b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_read_file_with_retry.pyindex 32db0f015d..535f9ef1d6 100644--- a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_read_file_with_retry.py+++ b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_read_file_with_retry.py@@ -10,7 +10,9 @@红线(本文件逐条锁定):- AbortError(HITL 中断)必须透传且不重试;- CancelledError 必须自然穿透(不吞取消信号);-- 重试后仍失败返回 "",与既有各节点 _read_file 行为一致。+- 重试后仍失败返回 "",与既有各节点 _read_file 行为一致;+- 工具以 success=False 结果返回(不抛异常)的瞬时锁错误必须按退避序列重试;+- 非瞬时失败结果(如文件不存在)不重试,直接按空内容处理。"""from __future__ import annotations@@ -48,6 +50,26 @@ class _FakeNode:return action+class _ToolOutputLike:+ """模拟 openjiuwen ToolOutput:失败以结果对象返回而不抛出。"""++ def __init__(+ self, success: bool, data: Any = None, error: str | None = None+ ) -> None:+ self.success = success+ self.data = data+ self.error = error++ def __str__(self) -> str:+ return f"success={self.success} data={self.data} error={self.error!r}"+++_LOCK_ERROR = (+ "file system operation execution error, execution: read_file, "+ "reason: Cannot operate on a closed database."+)++@pytest.mark.asyncioasync def test_retry_success_after_transient_error():node = _FakeNode(@@ -117,3 +139,47 @@ async def test_failed_result_parsed_as_empty():node = _FakeNode(script=[{"success": False}])text = await PptCommon.read_file_with_retry(node, "a.md")assert text == ""+++async def test_transient_result_failure_retries_and_recovers(monkeypatch):+ monkeypatch.setattr(PptCommon, "_TRANSIENT_LOCK_RETRY_DELAYS", (0.0, 0.0, 0.0))+ node = _FakeNode(+ script=[+ _ToolOutputLike(success=False, error=_LOCK_ERROR),+ _ToolOutputLike(success=True, data={"content": "# 大纲"}),+ ]+ )+ text = await PptCommon.read_file_with_retry(node, "a/outline.md", log_prefix="[P5]")+ assert text == "# 大纲"+ assert len(node.calls) == 2+++async def test_transient_result_failure_exhausts_retries(monkeypatch):+ monkeypatch.setattr(PptCommon, "_TRANSIENT_LOCK_RETRY_DELAYS", (0.0, 0.0, 0.0))+ node = _FakeNode(+ script=[+ _ToolOutputLike(success=False, error=_LOCK_ERROR),+ _ToolOutputLike(success=False, error=_LOCK_ERROR),+ _ToolOutputLike(success=False, error=_LOCK_ERROR),+ _ToolOutputLike(success=False, error=_LOCK_ERROR),+ ]+ )+ text = await PptCommon.read_file_with_retry(node, "a/outline.md", log_prefix="[P6]")+ assert text == ""+ assert len(node.calls) == 4+++async def test_non_transient_result_failure_not_retried():+ node = _FakeNode(+ script=[+ _ToolOutputLike(+ success=False, error="[Errno 2] No such file or directory: 'a/missing.md'"+ ),+ ]+ )+ text = await PptCommon.read_file_with_retry(node, "a/missing.md", log_prefix="[P8]")+ assert text == ""+ assert len(node.calls) == 1