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(agentserver): plan 绑定补丁防残留 CoreTask 撞库自愈,异常路径补告警日志
d30029696232faae58ffa
diff --git a/jiuwenswarm/common/deepagent_task_plan_binding_patch.py b/jiuwenswarm/common/deepagent_task_plan_binding_patch.pydeleted file mode 100644index 78f0131de1..0000000000--- a/jiuwenswarm/common/deepagent_task_plan_binding_patch.py+++ /dev/null@@ -1,89 +0,0 @@-# coding: utf-8-"""Bind interaction-loop continuation rounds to TaskPlan pending tasks.--openjiuwen ``DeepAgent._execute_round`` submits every round with a random-uuid task id, so the executor never marks TaskPlan tasks and the outer loop-spins forever on ``_has_remaining_tasks`` — holding the output lease, which-makes every new user message return an empty instant completion. This patch-restores the task-id resolution the non-interaction path already does.-"""-from __future__ import annotations--from typing import Any, Optional--from openjiuwen.core.common.logging import logger--__all__ = [- "apply_deepagent_task_plan_binding_patch",- "remove_deepagent_task_plan_binding_patch",-]--_PATCHED = False-_original_run_one_round: Any = None---def _resolve_plan_task_id(agent: Any, session: Any, work: Any) -> Optional[str]:- """Return the TaskPlan's next pending task id for a continuation round."""- if getattr(work, "kind", None) != "user":- return None- if getattr(work, "is_follow_up", False):- return None- if getattr(work, "reset_loop", True):- return None- if session is None:- return None- try:- state = agent.load_state(session)- plan = getattr(state, "task_plan", None)- if plan is None:- return None- return plan.get_next_task().id if plan.get_next_task() is not None else None- except Exception:- return None---def _make_patched_run_one_round(original: Any) -> Any:- async def _run_one_round_bound_to_plan(self: Any, work: Any, task_id: str, session: Any) -> Any:- resolved = _resolve_plan_task_id(self, session, work)- if resolved and resolved != task_id:- active = self._active_interaction_round- if active is not None and active.work is work:- # 保持取消定向与实际注册的调度任务 id 一致- active.task_id = resolved- task_id = resolved- return await original(self, work, task_id, session)-- return _run_one_round_bound_to_plan---def apply_deepagent_task_plan_binding_patch() -> None:- """Bind interaction continuation rounds to TaskPlan tasks. Idempotent."""- global _PATCHED, _original_run_one_round- if _PATCHED:- return- _PATCHED = True-- from openjiuwen.harness.deep_agent import DeepAgent-- _original_run_one_round = DeepAgent.run_one_round- setattr(- DeepAgent,- "run_one_round",- _make_patched_run_one_round(_original_run_one_round),- )- logger.info(- "[deepagent-plan-binding] patch applied "- "(interaction continuation rounds bind to TaskPlan pending tasks)",- )---def remove_deepagent_task_plan_binding_patch() -> None:- """Undo the patch. Test-only; production never removes it."""- global _PATCHED, _original_run_one_round- if not _PATCHED or _original_run_one_round is None:- return- from openjiuwen.harness.deep_agent import DeepAgent-- setattr(DeepAgent, "run_one_round", _original_run_one_round)- _original_run_one_round = None- _PATCHED = Falsediff --git a/jiuwenswarm/server/runtime/agent_adapter/deepagent_task_plan_binding_patch.py b/jiuwenswarm/server/runtime/agent_adapter/deepagent_task_plan_binding_patch.pynew file mode 100644index 0000000000..d4f9823c18--- /dev/null+++ b/jiuwenswarm/server/runtime/agent_adapter/deepagent_task_plan_binding_patch.py@@ -0,0 +1,181 @@+# coding: utf-8+"""Bind interaction-loop continuation rounds to TaskPlan pending tasks.++openjiuwen ``DeepAgent._execute_round`` submits every round with a random+uuid task id, so the executor never marks TaskPlan tasks and the outer loop+spins forever on ``_has_remaining_tasks`` — holding the output lease, which+makes every new user message return an empty instant completion. This patch+restores the task-id resolution the non-interaction path already does.++Occupancy self-healing: cancelling a bound round during its SUBMITTED window+(scheduler has not picked it up yet) marks the CoreTask CANCELED without+running the executor, so the TaskPlan item stays PENDING while TaskManager+never removes the terminal CoreTask. Re-binding that id would make+``add_task`` raise "already exists!" on every continuation round — an+unhealable error-round spin. When the resolver meets such a terminal+occupant it marks the plan item cancelled (same semantics as the executor's+WORKING-cancel path) and moves on to the next pending item, so the loop+converges and the session self-heals.+"""+from __future__ import annotations++from typing import Any, Optional++from openjiuwen.core.common.logging import logger++__all__ = [+ "apply_deepagent_task_plan_binding_patch",+ "remove_deepagent_task_plan_binding_patch",+]++_PATCHED = False+_original_run_one_round: Any = None+++async def _lookup_core_task(agent: Any, task_id: str) -> Optional[Any]:+ """Return the CoreTask occupying task_id in TaskManager, or None.++ Returns None when no task loop controller is bound yet (nothing can be+ occupied). Lookup errors propagate to the caller's fallback handling.+ """+ controller = getattr(agent, "loop_controller", None)+ task_manager = (+ getattr(controller, "task_manager", None)+ if controller is not None+ else None+ )+ if task_manager is None:+ return None++ from openjiuwen.core.controller.modules.task_manager import TaskFilter++ tasks = await task_manager.get_task(TaskFilter(task_id=task_id))+ return tasks[0] if tasks else None+++def _is_terminal_core_task(core_task: Any) -> bool:+ """Whether the occupying CoreTask is in a terminal status.++ Terminal tasks are never removed from TaskManager and can never be+ re-registered (add_task raises "already exists!").+ """+ from openjiuwen.core.controller.schema.task import TaskStatus++ return getattr(core_task, "status", None) in (+ TaskStatus.CANCELED,+ TaskStatus.COMPLETED,+ TaskStatus.FAILED,+ )+++async def _resolve_plan_task_id(agent: Any, session: Any, work: Any) -> Optional[str]:+ """Return the TaskPlan's next pending task id for a continuation round."""+ if getattr(work, "kind", None) != "user":+ return None+ if getattr(work, "is_follow_up", False):+ return None+ if getattr(work, "reset_loop", True):+ return None+ if session is None:+ return None+ try:+ state = agent.load_state(session)+ plan = getattr(state, "task_plan", None)+ if plan is None:+ return None+ # Bounded: each iteration either returns or cancels one plan item.+ for _ in range(max(len(getattr(plan, "tasks", []) or []), 1)):+ next_task = plan.get_next_task()+ if next_task is None:+ return None+ occupied = await _lookup_core_task(agent, next_task.id)+ if occupied is None:+ return next_task.id+ if _is_terminal_core_task(occupied):+ # Zombie CoreTask (e.g. cancel during the SUBMITTED window):+ # the id can never be re-registered, so this plan item can+ # never run. Mark it cancelled to unblock the loop, then try+ # the next pending item.+ plan.mark_cancelled(+ next_task.id,+ reason=(+ "core task already in terminal status "+ f"({getattr(occupied, 'status', None)}); "+ "round was cancelled before start"+ ),+ )+ agent.save_state(session, state)+ logger.warning(+ "[deepagent-plan-binding] plan task %s occupied by terminal "+ "core task (status=%s session=%s); marked cancelled, "+ "resolving next pending task",+ next_task.id,+ getattr(occupied, "status", None),+ getattr(session, "get_session_id", lambda: None)(),+ )+ continue+ # SUBMITTED/WORKING/... occupation: an in-flight round owns this+ # id and will mark the plan item itself; fall back to raw task_id.+ logger.warning(+ "[deepagent-plan-binding] plan task %s occupied by in-flight "+ "core task (status=%s session=%s); fallback to raw task_id",+ next_task.id,+ getattr(occupied, "status", None),+ getattr(session, "get_session_id", lambda: None)(),+ )+ return None+ return None+ except Exception:+ logger.warning(+ "[deepagent-plan-binding] resolve plan task failed, fallback to raw task_id",+ exc_info=True,+ )+ return None+++def _make_patched_run_one_round(original: Any) -> Any:+ async def _run_one_round_bound_to_plan(self: Any, work: Any, task_id: str, session: Any) -> Any:+ resolved = await _resolve_plan_task_id(self, session, work)+ if resolved and resolved != task_id:+ # getattr:跨类读受保护成员不触发 protected-access(同 mcp_call_timeout_patch 惯例)+ active = getattr(self, "_active_interaction_round", None)+ if active is not None and active.work is work:+ # 保持取消定向与实际注册的调度任务 id 一致+ active.task_id = resolved+ task_id = resolved+ return await original(self, work, task_id, session)++ return _run_one_round_bound_to_plan+++def apply_deepagent_task_plan_binding_patch() -> None:+ """Bind interaction continuation rounds to TaskPlan tasks. Idempotent."""+ global _PATCHED, _original_run_one_round+ if _PATCHED:+ return+ _PATCHED = True++ from openjiuwen.harness.deep_agent import DeepAgent++ _original_run_one_round = DeepAgent.run_one_round+ setattr(+ DeepAgent,+ "run_one_round",+ _make_patched_run_one_round(_original_run_one_round),+ )+ logger.info(+ "[deepagent-plan-binding] patch applied "+ "(interaction continuation rounds bind to TaskPlan pending tasks)",+ )+++def remove_deepagent_task_plan_binding_patch() -> None:+ """Undo the patch. Test-only; production never removes it."""+ global _PATCHED, _original_run_one_round+ if not _PATCHED or _original_run_one_round is None:+ return+ from openjiuwen.harness.deep_agent import DeepAgent++ setattr(DeepAgent, "run_one_round", _original_run_one_round)+ _original_run_one_round = None+ _PATCHED = Falsediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 51cd232240..e22f0a45c8 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -487,7 +487,7 @@ from jiuwenswarm.common.mcp_config import (unregister_live_office_claw_tool_instance,validate_office_claw_mcp_config,)-from jiuwenswarm.common.deepagent_task_plan_binding_patch import (+from jiuwenswarm.server.runtime.agent_adapter.deepagent_task_plan_binding_patch import (apply_deepagent_task_plan_binding_patch,)from jiuwenswarm.common.mcp_call_timeout_patch import apply_mcp_call_timeout_patchdiff --git a/tests/unit_tests/agentserver/test_deepagent_task_plan_binding_patch.py b/tests/unit_tests/agentserver/test_deepagent_task_plan_binding_patch.pyindex e9828e82d7..d4b25b81c9 100644--- a/tests/unit_tests/agentserver/test_deepagent_task_plan_binding_patch.py+++ b/tests/unit_tests/agentserver/test_deepagent_task_plan_binding_patch.py@@ -10,6 +10,11 @@ from unittest.mock import AsyncMockimport pytest+from openjiuwen.core.controller.modules.task_manager import TaskFilter+from openjiuwen.core.controller.schema.task import (+ Task as CoreTask,+ TaskStatus as CoreTaskStatus,+)from openjiuwen.core.single_agent import AgentCard, create_agent_sessionfrom openjiuwen.harness.deep_agent import DeepAgentfrom openjiuwen.harness.schema.interaction import (@@ -17,9 +22,13 @@ from openjiuwen.harness.schema.interaction import (RoundWorkItem,)from openjiuwen.harness.schema.task import TaskPlan, TodoItem, TodoStatus+from openjiuwen.harness.task_loop.task_loop_event_executor import (+ DEEP_TASK_TYPE,+)-from jiuwenswarm.common.deepagent_task_plan_binding_patch import (+from jiuwenswarm.server.runtime.agent_adapter.deepagent_task_plan_binding_patch import (_make_patched_run_one_round,+ _resolve_plan_task_id,apply_deepagent_task_plan_binding_patch,remove_deepagent_task_plan_binding_patch,)@@ -155,13 +164,117 @@ async def test_active_round_task_id_rebound_to_plan_task():@pytest.mark.asyncioasync def test_patch_apply_remove_roundtrip():- """验证 补丁 apply/remove 可往返且幂等。"""+ """验证 补丁 apply/remove 可往返且幂等(断言失败也不泄漏全局补丁状态)。"""original = DeepAgent.run_one_round- apply_deepagent_task_plan_binding_patch()- apply_deepagent_task_plan_binding_patch()- assert DeepAgent.run_one_round is not original-- remove_deepagent_task_plan_binding_patch()- remove_deepagent_task_plan_binding_patch()+ try:+ apply_deepagent_task_plan_binding_patch()+ apply_deepagent_task_plan_binding_patch()+ assert DeepAgent.run_one_round is not original+ finally:+ remove_deepagent_task_plan_binding_patch()+ remove_deepagent_task_plan_binding_patch()assert DeepAgent.run_one_round is original+++async def _occupy_plan_task(+ agent: DeepAgent, session, task_id: str, status: CoreTaskStatus+) -> None:+ """在已就绪的控制器上注入残留 CoreTask(模拟 SUBMITTED 窗口取消等残留)。"""+ await agent.loop_controller.task_manager.add_task(+ CoreTask(+ session_id=session.get_session_id(),+ task_id=task_id,+ task_type=DEEP_TASK_TYPE,+ description="occupied",+ status=status,+ )+ )+++async def test_zombie_terminal_core_task_marks_plan_cancelled_and_binds_next():+ """验证 终态残留占用时标记 plan 任务取消并绑定下一 pending 任务。"""+ agent, session = _make_agent_with_plan()+ state = agent.load_state(session)+ state.task_plan.tasks.append(+ TodoItem(id="t3", content="next-task", activeForm="next-task",+ status=TodoStatus.PENDING),+ )+ agent.save_state(session, state)+ _coordinator, controller = await agent.prepare_interaction_task_loop(session)+ # 模拟 SUBMITTED 窗口取消后残留的终态 CoreTask+ await _occupy_plan_task(agent, session, "t2", CoreTaskStatus.CANCELED)++ resolved = await _resolve_plan_task_id(agent, session, _continuation_work())++ assert resolved == "t3"+ plan = agent.load_state(session).task_plan+ assert plan.get_task("t2").status is TodoStatus.CANCELLED+ assert plan.get_task("t3").status is TodoStatus.PENDING++ await controller.stop()+++async def test_all_pending_zombie_marks_all_cancelled_returns_none():+ """验证 全部 pending 被终态残留占用时全部标记取消,循环可收敛。"""+ agent, session = _make_agent_with_plan()+ _coordinator, controller = await agent.prepare_interaction_task_loop(session)+ await _occupy_plan_task(agent, session, "t2", CoreTaskStatus.CANCELED)++ resolved = await _resolve_plan_task_id(agent, session, _continuation_work())++ assert resolved is None+ plan = agent.load_state(session).task_plan+ assert plan.get_task("t2").status is TodoStatus.CANCELLED+ assert agent._has_remaining_tasks(session) is False++ await controller.stop()+++async def test_inflight_core_task_falls_back_to_raw_task_id():+ """验证 非终态(在飞)占用时回退原始 task_id,plan 任务保持不变。"""+ agent, session = _make_agent_with_plan()+ _coordinator, controller = await agent.prepare_interaction_task_loop(session)+ await _occupy_plan_task(agent, session, "t2", CoreTaskStatus.WORKING)++ resolved = await _resolve_plan_task_id(agent, session, _continuation_work())++ assert resolved is None+ plan = agent.load_state(session).task_plan+ assert plan.get_task("t2").status is TodoStatus.PENDING++ await controller.stop()+++async def test_continuation_round_recovers_from_zombie_and_converges(plan_binding_patch):+ """验证 僵尸占用后续轮自愈:跳过僵尸任务、执行下一任务、循环收敛。"""+ agent, session = _make_agent_with_plan()+ state = agent.load_state(session)+ state.task_plan.tasks.append(+ TodoItem(id="t3", content="next-task", activeForm="next-task",+ status=TodoStatus.PENDING),+ )+ agent.save_state(session, state)+ _coordinator, controller = await agent.prepare_interaction_task_loop(session)+ await _occupy_plan_task(agent, session, "t2", CoreTaskStatus.CANCELED)++ outcome = await agent.run_one_round(+ _continuation_work(), uuid.uuid4().hex, session+ )++ plan = agent.load_state(session).task_plan+ assert plan.get_task("t2").status is TodoStatus.CANCELLED+ assert plan.get_task("t3").status is TodoStatus.COMPLETED+ assert plan.get_next_task() is None+ assert outcome.next_work is None+ assert outcome.error_code is None++ # 僵尸 CoreTask 仍在 TaskManager,但本轮注册的任务是 t3 而非 t2+ registered = await controller.task_manager.get_task(TaskFilter(task_id="t3"))+ assert registered and registered[0].task_id == "t3"++ await controller.stop()