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): safe_overwrite_file 检测 write_file success=False 瞬态锁错误并退避重试
d30029696d3d7eb089771
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 87aa410273..62b369b25d 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@@ -46,6 +46,70 @@ def is_write_protocol_error(exc: BaseException) -> bool:return any(marker in text for marker in _WRITE_PROTOCOL_MARKERS)+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)+++def is_transient_lock_failure(failure_text: str) -> bool:+ lowered = (failure_text or "").lower()+ return any(marker in lowered for marker in TRANSIENT_LOCK_ERROR_MARKERS)+++def tool_result_failure_text(result: Any) -> str:+ 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 ""+++async def wait_for_transient_retry(+ log_prefix: str,+ attempt: int,+ path: str,+ failure_text: str,+ *,+ action: str = "读取文件",+) -> bool:+ """瞬时锁错误按退避间隔等待重试;额度耗尽返回 False。"""+ if attempt > len(TRANSIENT_LOCK_RETRY_DELAYS):+ logger.warning(+ "%s %s瞬时锁错误(重试耗尽) path=%s: %s",+ log_prefix,+ action,+ path,+ failure_text,+ )+ return False+ delay = TRANSIENT_LOCK_RETRY_DELAYS[attempt - 1]+ logger.warning(+ "%s %s瞬时锁错误(第%d次),%.1fs后重试 path=%s: %s",+ log_prefix,+ action,+ attempt,+ delay,+ path,+ failure_text,+ )+ await asyncio.sleep(delay)+ return True++async def get_page_path_lock(path: str) -> asyncio.Lock:"""Process-wide per-path lock so P8.1 / P8.2 share the same serialization."""key = _normalize_page_path_key(path) or str(path or "")@@ -72,7 +136,7 @@ async def safe_overwrite_file_impl(already_locked: bool = False,log_prefix: str = "[ppt]",) -> bool:- """Read-then-write under path lock; retry once on host write-protocol errors."""+ """Read-then-write under path lock; retry on protocol errors and transient lock failures."""if not path:return Falseif not node.has_tool("write_file"):@@ -80,8 +144,9 @@ async def safe_overwrite_file_impl(return Falseasync def _body() -> bool:- last_exc: BaseException | None = None- for attempt in range(2):+ attempt = 0+ while True:+ attempt += 1try:if node.has_tool("read_file"):try:@@ -89,22 +154,19 @@ async def safe_overwrite_file_impl(except Exception as read_exc:if isinstance(read_exc, AbortError):raise- # 文件尚不存在时允许继续覆盖写logger.debug("%s 覆盖写前 read 跳过 path=%s: %s",log_prefix,path,read_exc,)- await node.call_tool("write_file", file_path=path, content=content)- # 写盘成功后主动让出事件循环,避免 P8 多页集中收尾时饿死 WS ping/pong。+ result = await node.call_tool("write_file", file_path=path, content=content)await asyncio.sleep(0)- return True+ failure = tool_result_failure_text(result)except Exception as exc:if isinstance(exc, AbortError):raise- last_exc = exc- if attempt == 0 and is_write_protocol_error(exc):+ if attempt == 1 and is_write_protocol_error(exc):logger.warning("%s write_file 协议冲突,同锁重试 path=%s: %s",log_prefix,@@ -112,11 +174,18 @@ async def safe_overwrite_file_impl(exc,)continue- logger.error("%s 写入文件失败 %s: %s", log_prefix, path, exc)+ failure = str(exc)++ if failure and is_transient_lock_failure(failure):+ if await wait_for_transient_retry(+ log_prefix, attempt, path, failure, action="写入文件",+ ):+ continuereturn False- if last_exc is not None:- logger.error("%s 写入文件失败 %s: %s", log_prefix, path, last_exc)- return False+ if failure:+ logger.error("%s 写入文件失败 %s: %s", log_prefix, path, failure)+ return False+ return Trueif already_locked:return await _body()@@ -408,67 +477,6 @@ 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,@@ -491,8 +499,8 @@ class PptCommon:except Exception as e:if isinstance(e, AbortError):raise- if cls._is_transient_lock_failure(str(e)):- if await cls._wait_for_transient_retry(log_prefix, attempt, path, str(e)):+ if is_transient_lock_failure(str(e)):+ if await wait_for_transient_retry(log_prefix, attempt, path, str(e)):continuereturn ""if attempt == 1:@@ -511,9 +519,9 @@ class PptCommon:)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(+ failure_text = tool_result_failure_text(result)+ if failure_text and is_transient_lock_failure(failure_text):+ if await wait_for_transient_retry(log_prefix, attempt, path, failure_text):continuediff --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 535f9ef1d6..96e7566d9e 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@@ -24,6 +24,7 @@ import pytestfrom jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortErrorfrom jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_common import PptCommon+import jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_common as ppt_commonclass _FakeNode:@@ -143,7 +144,7 @@ async def test_failed_result_parsed_as_empty():@pytest.mark.asyncioasync def test_transient_result_failure_retries_and_recovers(monkeypatch):- monkeypatch.setattr(PptCommon, "_TRANSIENT_LOCK_RETRY_DELAYS", (0.0, 0.0, 0.0))+ monkeypatch.setattr(ppt_common, "TRANSIENT_LOCK_RETRY_DELAYS", (0.0, 0.0, 0.0))node = _FakeNode(script=[_ToolOutputLike(success=False, error=_LOCK_ERROR),@@ -157,7 +158,7 @@ async def test_transient_result_failure_retries_and_recovers(monkeypatch):@pytest.mark.asyncioasync def test_transient_result_failure_exhausts_retries(monkeypatch):- monkeypatch.setattr(PptCommon, "_TRANSIENT_LOCK_RETRY_DELAYS", (0.0, 0.0, 0.0))+ monkeypatch.setattr(ppt_common, "TRANSIENT_LOCK_RETRY_DELAYS", (0.0, 0.0, 0.0))node = _FakeNode(script=[_ToolOutputLike(success=False, error=_LOCK_ERROR),@@ -176,7 +177,8 @@ 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'"+ success=False,+ error="[Errno 2] No such file or directory: 'a/missing.md'",),])diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_research_and_page_io.py b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_research_and_page_io.pyindex 8d623ec7bb..4bc43cef31 100644--- a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_research_and_page_io.py+++ b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_research_and_page_io.py@@ -4,6 +4,7 @@from __future__ import annotations+import asynciofrom typing import Anyimport pytest@@ -71,7 +72,9 @@ def test_parse_validate_research_output_extracts_invalid_pages():def test_is_write_protocol_error():assert is_write_protocol_error(- Exception("File has been modified since read, either by the user or by a linter.")+ Exception(+ "File has been modified since read, either by the user or by a linter."+ ))assert is_write_protocol_error(Exception("File has not been fully read yet. You have read 0 of 0 lines.")@@ -116,6 +119,121 @@ async def test_safe_overwrite_retries_protocol_error():assert node.reads >= 2+class _TransientLockNode:+ """write_file 首次返回 success=False(closed database),重试后成功。"""++ def __init__(self) -> None:+ self.writes = 0+ self.fail_transient_count = 1+ self.tools = {"read_file", "write_file"}++ def has_tool(self, name: str) -> bool:+ return name in self.tools++ async def call_tool(self, name: str, **kwargs: Any) -> Any:+ if name == "read_file":+ return {"content": "<html></html>"}+ if name == "write_file":+ self.writes += 1+ if self.fail_transient_count > 0:+ self.fail_transient_count -= 1+ return type(+ "R",+ (),+ {+ "success": False,+ "data": None,+ "error": (+ "file system operation execution error, "+ "execution: write_file, reason: "+ "Cannot operate on a closed database."+ ),+ },+ )()+ return {"ok": True}+ raise AssertionError(f"unexpected tool {name}")+++async def test_safe_overwrite_retries_transient_lock_failure_result(+ monkeypatch: pytest.MonkeyPatch,+):+ """验证 write_file 返回 success=False(closed database)时按退避重试,最终成功。"""+ import jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_common as ppt_common++ delays: list[float] = []+ real_sleep = asyncio.sleep++ async def _fast_sleep(delay: float) -> None:+ delays.append(delay)+ await real_sleep(0)++ monkeypatch.setattr(ppt_common.asyncio, "sleep", _fast_sleep)++ node = _TransientLockNode()+ ok = await safe_overwrite_file_impl(+ node,+ r"D:\tmp\page-1.pptx.html",+ "<html>ok</html>",+ log_prefix="[test]",+ )+ assert ok is True+ assert node.writes == 2+ assert 0.5 in delays+++class _AlwaysTransientLockNode:+ """write_file 始终返回 success=False(closed database)。"""++ tools = {"read_file", "write_file"}++ def has_tool(self, name: str) -> bool:+ return name in self.tools++ async def call_tool(self, name: str, **kwargs: Any) -> Any:+ if name == "read_file":+ return {"content": "<html></html>"}+ if name == "write_file":+ return type(+ "R",+ (),+ {+ "success": False,+ "data": None,+ "error": (+ "file system operation execution error, "+ "execution: write_file, reason: "+ "Cannot operate on a closed database."+ ),+ },+ )()+ raise AssertionError(f"unexpected tool {name}")+++async def test_safe_overwrite_transient_lock_failure_exhausted(+ monkeypatch: pytest.MonkeyPatch,+):+ """验证 write_file 持续返回 closed database 时重试耗尽后返回 False。"""+ import jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_common as ppt_common++ real_sleep = asyncio.sleep++ async def _fast_sleep(delay: float) -> None:+ await real_sleep(0)++ monkeypatch.setattr(ppt_common.asyncio, "sleep", _fast_sleep)++ node = _AlwaysTransientLockNode()+ ok = await safe_overwrite_file_impl(+ node,+ r"D:\tmp\page-1.pptx.html",+ "<html>ok</html>",+ log_prefix="[test]",+ )+ assert ok is False++def test_is_slide_exportable_requires_main_in_ppt_slide():bad = "<html><body><main>x</main></body></html>"good = (@@ -131,7 +249,7 @@ async def test_reconcile_missing_pages_clears_false_positives(tmp_path):pages_dir = tmp_path / "pages"pages_dir.mkdir()html = (- '<!DOCTYPE html><html><body>'+ "<!DOCTYPE html><html><body>"'<div class="ppt-slide h-[720px]">''<main class="flex-1"><section>content</section></main>'"</div></body></html>"