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(session): 修复 history 落盘阻塞事件循环导致模型调用失败
d300296966a17c040d422
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex cd10797e40..e0a23689e2 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -28,7 +28,7 @@ from contextvars import ContextVar, Tokenfrom dataclasses import dataclass, replacefrom pathlib import Pathfrom shutil import which-from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, List, Optional, Tuple, cast+from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, ClassVar, List, Optional, Tuple, castfrom urllib.parse import quote_plusimport yaml@@ -16696,6 +16696,9 @@ class JiuWenSwarmDeepAdapter:)return False+ # 进程内已完成卡一次性守卫:同 (session, goal) 只落盘一次;跨进程重复由磁盘检查兜底+ _GOAL_COMPLETED_PERSISTED: ClassVar[set[tuple[str, str]]] = set()+@staticmethoddef _record_goal_completed_history_if_needed(*,@@ -16716,6 +16719,8 @@ class JiuWenSwarmDeepAdapter:if not goal_id:returnsid = (session_id or "default").strip() or "default"+ if (sid, goal_id) in JiuWenSwarmDeepAdapter._GOAL_COMPLETED_PERSISTED:+ returnif JiuWenSwarmDeepAdapter._goal_completed_history_exists(sid, goal_id):return@@ -16743,6 +16748,7 @@ class JiuWenSwarmDeepAdapter:"evidence": evidence,},)+ JiuWenSwarmDeepAdapter._GOAL_COMPLETED_PERSISTED.add((sid, goal_id))@staticmethoddef _interaction_goal_updated_payload(payload: Any) -> dict[str, Any]:diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex 70ce53a80b..6004c1318b 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport atexitimport datetimeimport logging@@ -19,7 +20,7 @@ from jiuwenswarm.common.utils import get_agent_sessions_dirlogger = logging.getLogger(__name__)_FILE_LOCK = threading.Lock()-_WRITE_QUEUE: queue.Queue[tuple[str, dict[str, Any], str | None]] = queue.Queue(maxsize=20000)+_WRITE_QUEUE: queue.Queue[tuple[str, list[dict[str, Any]], str | None]] = queue.Queue(maxsize=20000)_WORKER_STARTED = False_WORKER_LOCK = threading.Lock()_LEGACY_HISTORY_FILENAME = "history.json"@@ -606,6 +607,9 @@ def write_history_records(if preserve_existing_formatelse get_write_history_path(session_id))+ # 整文件重写前先排空异步写队列,避免重写结果与排队中的 append 交错+ _ensure_worker_started()+ _WRITE_QUEUE.join()with _FILE_LOCK:_write_records_to_path(path, records)return path@@ -753,9 +757,24 @@ def read_session_history_records(session_id: str) -> list[dict[str, Any]]:def _batch_write_items(session_id: str, items: list[dict], sessions_root: str | None) -> None:- """批量写入 history.json(一次 open 写多行)。_FILE_LOCK 串行化磁盘写。"""+ """批量写入 history.json(一次 open 写多行)。_FILE_LOCK 串行化磁盘写。++ 事件循环线程上只入队,由 session-history-writer 单线程落盘;队列满时+ 退化为调用方同步写。+ """if not items:return+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ pass+ else:+ _ensure_worker_started()+ try:+ _WRITE_QUEUE.put_nowait((session_id, items, sessions_root))+ return+ except queue.Full:+ passwith _FILE_LOCK:if use_legacy_history_json():target_path = _ensure_legacy_json_bootstrap(session_id, sessions_root=sessions_root)@@ -768,10 +787,6 @@ def _batch_write_items(session_id: str, items: list[dict], sessions_root: str |fh.write("\n")-def _write_item(session_id: str, item: dict[str, Any], sessions_root: str | None = None) -> None:- _batch_write_items(session_id, [item], sessions_root)--def _ensure_worker_started() -> None:global _WORKER_STARTEDif _WORKER_STARTED:@@ -782,9 +797,9 @@ def _ensure_worker_started() -> None:def _worker() -> None:while True:- sid, item, sessions_root = _WRITE_QUEUE.get()+ sid, items, sessions_root = _WRITE_QUEUE.get()try:- _write_item(sid, item, sessions_root)+ _batch_write_items(sid, items, sessions_root)except Exception as exc: # noqa: BLE001logger.warning("history 异步写入失败: %s", exc)finally:@@ -1173,11 +1188,7 @@ def append_history_record(_route_event(sid, item, et, sessions_root_s)except Exception as exc: # noqa: BLE001logger.warning("history 缓冲写入失败,降级直写: %s", exc)- _ensure_worker_started()- try:- _WRITE_QUEUE.put_nowait((sid, item, sessions_root_s))- except queue.Full:- _write_item(sid, item, sessions_root_s)+ _batch_write_items(sid, [item], sessions_root_s)# 工具调用成败统计:tool_call/tool_result 事件后防抖触发后台增量扫描(不阻塞主流程)if et in ("chat.tool_call", "chat.tool_result"):diff --git a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py b/tests/unit_tests/agentserver/test_goal_runtime_adapter.pyindex cb5557b563..7c641f8a82 100644--- a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py+++ b/tests/unit_tests/agentserver/test_goal_runtime_adapter.py@@ -653,6 +653,7 @@ def test_record_goal_set_history_writes_objective_flags(monkeypatch: pytest.Monkdef test_record_goal_completed_history_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:captured: list[dict] = []+ monkeypatch.setattr(JiuWenSwarmDeepAdapter, "_GOAL_COMPLETED_PERSISTED", set())monkeypatch.setattr("jiuwenswarm.server.runtime.agent_adapter.interface_deep.append_history_record",lambda **kwargs: captured.append(kwargs),@@ -677,6 +678,22 @@ def test_record_goal_completed_history_is_idempotent(monkeypatch: pytest.MonkeyPassert captured[0]["extra"]["id"] == "goal-completed-g1"assert captured[0]["content"].startswith("goal.completed:")+ # 异步落盘未完成(磁盘仍为空)时同 goal 再次触发,由进程内守卫去重+ JiuWenSwarmDeepAdapter._record_goal_completed_history_if_needed(+ session_id="s1",+ channel_id="web",+ channel_metadata=None,+ mode="agent",+ goal_payload={+ "goal_id": "g1",+ "status": "completed",+ "last_assessment": {"evidence": "all done"},+ },+ )+ assert len(captured) == 1++ # 跨进程场景:守卫为空、完成卡已在磁盘,由磁盘检查去重+ monkeypatch.setattr(JiuWenSwarmDeepAdapter, "_GOAL_COMPLETED_PERSISTED", set())monkeypatch.setattr("jiuwenswarm.server.runtime.agent_adapter.interface_deep.load_history_records",lambda _sid: [diff --git a/tests/unit_tests/test_session_history_event_loop_stall.py b/tests/unit_tests/test_session_history_event_loop_stall.pynew file mode 100644index 0000000000..361891a16e--- /dev/null+++ b/tests/unit_tests/test_session_history_event_loop_stall.py@@ -0,0 +1,145 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++# pylint: disable=protected-access++"""验证 append_history_record 在 history 大文件慢 open 场景下不阻塞事件循环。"""++from __future__ import annotations++import asyncio+import json+import sys+import threading+import time+from pathlib import Path++import pytest++from jiuwenswarm.server.runtime.session import session_history as sh++_SIMULATED_SLOW_OPEN_SECONDS = 1.5+_HEARTBEAT_INTERVAL = 0.05+++def _stop_flush_thread():+ sh._flush_stop_event.set()+ t = getattr(sh, "_FLUSH_THREAD", None)+ if t is not None and t.is_alive() and t is not threading.current_thread():+ t.join(timeout=2.0)+ sh._flush_stop_event.clear()+++def _clear_buffer_state():+ sh._session_buffer.clear()+ sh._session_buffer_type.clear()+ sh._session_buffer_request_id.clear()+ sh._session_buffer_root.clear()+ sh._session_tool_update_buffer.clear()+ sh._session_tool_update_root.clear()+ sh._session_pending.clear()+ sh._FLUSH_THREAD_STARTED = False+ sh._FLUSH_THREAD = None+ sh._SHUTDOWN_DONE = False+ sh._flush_stop_event.clear()++[email protected](autouse=True)+def _isolated_history_state(monkeypatch):+ _stop_flush_thread()+ _clear_buffer_state()+ monkeypatch.delenv("JIUWENSWARM_USE_LEGACY_HISTORY_JSON", raising=False)+ yield+ _stop_flush_thread()+ _clear_buffer_state()+++async def test_append_history_record_keeps_event_loop_responsive_on_slow_open(+ monkeypatch, tmp_path+):+ sessions_root = str(tmp_path)+ sid = "sess_repro_001"+ history_path = Path(sessions_root) / sid / "history.json"+ history_path.parent.mkdir(parents=True)+ big_content = "x" * (2 * 1024 * 1024)+ history_path.write_text(+ json.dumps([{"id": "seed", "role": "user", "content": big_content}]),+ encoding="utf-8",+ )++ original_open = Path.open++ def slow_open(self, *args, **kwargs):+ mode = str(args[0]) if args else str(kwargs.get("mode", "r"))+ if "r" in mode and self == history_path:+ time.sleep(_SIMULATED_SLOW_OPEN_SECONDS)+ return original_open(self, *args, **kwargs)++ monkeypatch.setattr(Path, "open", slow_open)++ ticks: list[float] = []++ async def heartbeat():+ while True:+ ticks.append(time.monotonic())+ await asyncio.sleep(_HEARTBEAT_INTERVAL)++ hb = asyncio.create_task(heartbeat())++ stacks: list[str] = []+ stop_watchdog = threading.Event()+ main_tid = threading.get_ident()++ def watchdog():+ while not stop_watchdog.is_set():+ frame = sys._current_frames().get(main_tid)+ if frame is not None:+ names = []+ f = frame+ while f is not None and len(names) < 10:+ names.append(f.f_code.co_name)+ f = f.f_back+ stacks.append(" <- ".join(names))+ stop_watchdog.wait(0.05)++ wd = threading.Thread(target=watchdog, daemon=True)+ wd.start()++ await asyncio.sleep(0.3)++ sh.append_history_record(+ session_id=sid,+ request_id="req-1",+ channel_id="officeclaw",+ role="assistant",+ content="tool result payload",+ timestamp=time.time(),+ event_type="chat.tool_result",+ extra={"tool_call_id": "call-1"},+ sessions_root=sessions_root,+ )++ await asyncio.sleep(0.3)+ hb.cancel()+ try:+ await hb+ except asyncio.CancelledError:+ pass+ stop_watchdog.set()+ wd.join(timeout=2.0)++ gaps = [b - a for a, b in zip(ticks, ticks[1:])]+ assert gaps, "heartbeat never ticked"+ max_gap = max(gaps)+ assert max_gap < _SIMULATED_SLOW_OPEN_SECONDS, (+ f"event loop stalled {max_gap:.2f}s during append; "+ "history write must run off the event loop"+ )+ assert not any(+ "_peek_first_non_ws_char" in s or "_write_records_to_path" in s+ for s in stacks+ ), "history disk I/O ran on the event loop thread"++ sh._WRITE_QUEUE.join()+ with open(history_path, "r", encoding="utf-8") as fh:+ lines = [ln for ln in fh.read().split("\n") if ln.strip()]+ assert any('"chat.tool_result"' in ln for ln in lines)