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(hitl): team runtime 世代校验,根治迟到取消/暂停误杀新回合
KevinLLLove6321d83f705e
diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.pyindex 1e39a4fad5..9f95636ace 100644--- a/jiuwenswarm/agents/harness/team/team_manager.py+++ b/jiuwenswarm/agents/harness/team/team_manager.py@@ -300,6 +300,11 @@ class TeamManager:# _cancel_requested 在 cancel_session_runtime 内即被 pop,活不到 waiter 醒来# 的时刻,故由本表跨清理存活到 waiter 查询,并在下一轮 stream task 注册时清除。self._session_terminal_states: dict[str, str] = {}+ # session_id → 单调递增的 runtime 世代号。每个新回合注册 pending runtime+ # (prepare_runtime_activation)时递增一次;cancel/pause 在入口捕获当前世代,+ # 并在破坏性步骤前校验——世代变了说明慢 await(如 30 人团队 Runner 清理+ # ~53s)期间已有新回合注册,本次迟到拆除必须放弃,不得误杀新回合。+ self._session_runtime_epochs: dict[str, int] = {}# 追踪当前正在执行的 pause 任务,供 cancel 抢占取消self._active_pause_tasks: dict[str, asyncio.Task] = {}self._active_team_names: dict[str, str] = {}@@ -368,6 +373,27 @@ class TeamManager:def clear_session_terminal_state(self, session_id: str) -> None:self._session_terminal_states.pop(session_id, None)+ def bump_session_runtime_epoch(self, session_id: str) -> int:+ """Advance and return the per-session runtime generation.++ Called once at the start of every new team round, when+ prepare_runtime_activation registers the pending runtime. Round-scoped+ teardown operations (cancel/pause) capture the epoch at entry and+ re-validate it before destructive steps: a changed epoch means a newer+ round started while the teardown was stuck in a slow await, so the late+ teardown must be abandoned instead of tearing down the new round.+ """+ epoch = self._session_runtime_epochs.get(session_id, 0) + 1+ self._session_runtime_epochs[session_id] = epoch+ return epoch++ def get_session_runtime_epoch(self, session_id: str) -> int:+ return self._session_runtime_epochs.get(session_id, 0)++ def _is_current_runtime_epoch(self, session_id: str, epoch: int) -> bool:+ """Return True when no new round has started since ``epoch`` was captured."""+ return self._session_runtime_epochs.get(session_id, 0) == epoch+def is_session_initialized(self, session_id: str) -> bool:"""Return whether the session has ever initialized a team runtime."""return session_id in self._initialized_sessions@@ -1066,9 +1092,12 @@ class TeamManager:reason="switch runtime: ",)self._pending_team_names[session_id] = team_name+ # 新回合起点:递增世代号。迟到的 cancel/pause 据此放弃拆除。+ self.bump_session_runtime_epoch(session_id)returnself._pending_team_names[session_id] = team_name+ self.bump_session_runtime_epoch(session_id)async def _wait_same_session_runner_runtime_released(self,@@ -2478,6 +2507,10 @@ class TeamManager:"[TeamManager] cancel_session_runtime 入口: session_id=%s reason=%s",session_id, reason,)+ # 世代校验(方案 epoch):在入口(一切慢 await 之前)捕获当前世代,+ # 后续破坏性步骤前逐一复核——期间若有新回合注册(世代已递增),+ # 说明本次 cancel 迟到,必须放弃拆除以免误杀新回合。+ target_epoch = self.get_session_runtime_epoch(session_id)# 通知正在执行的 pause 操作中止自身,让 cancel 尽快获取 lifecycle lockself._cancel_requested[session_id] = True@@ -2503,6 +2536,19 @@ class TeamManager:language=language,)+ # 世代校验点 1:上面的 settle 是慢 await(Runner 清理可达数十秒),+ # 期间新回合可能已注册。世代变了 → 本次 cancel 迟到:放弃一切拆除,+ # 不写终态记录(否则新回合的 waiter 会把正常退出误报为取消),+ # 也不清理新回合的 checkpoint 断点(那属于新回合的审批状态)。+ if not self._is_current_runtime_epoch(session_id, target_epoch):+ self._cancel_requested.pop(session_id, None)+ logger.info(+ "[TeamManager] %slate cancel superseded by newer round: session_id=%s",+ reason,+ session_id,+ )+ return False+# 如果 lifecycle lock 被其他操作(如 pause)持有,先尝试直接停止 Runner# 以避免 cancel 被 pause 阻塞长达数分钟lock = self._get_lifecycle_lock(session_id)@@ -2521,6 +2567,17 @@ class TeamManager:# 清理 cancel_requested 标志self._cancel_requested.pop(session_id, None)+ # 世代校验点 2:等锁期间新回合仍可能注册(register_stream_task+ # 是同步方法,不拿本锁)。迟到 → 放弃拆除且不写终态记录。+ if not self._is_current_runtime_epoch(session_id, target_epoch):+ logger.info(+ "[TeamManager] %slate cancel superseded by newer round "+ "(inside lifecycle lock): session_id=%s",+ reason,+ session_id,+ )+ return False+has_stream_task = session_id in self._stream_taskshas_local_team_runtime = self._has_local_team_runtime(session_id)has_team_runtime = (@@ -2657,6 +2714,9 @@ class TeamManager:tearing down the foreground stream task and parking the Runner-ownedruntime in paused state so a later `chat.send` can resume it."""+ # 世代校验(方案 epoch):入口捕获当前世代,拆除前复核——+ # 慢 await 期间新回合已注册则本次 pause 迟到,放弃拆除。+ target_epoch = self.get_session_runtime_epoch(session_id)async with self._get_lifecycle_lock(session_id):has_stream_task = session_id in self._stream_taskshas_local_team_runtime = self._has_local_team_runtime(session_id)@@ -2677,6 +2737,17 @@ class TeamManager:)return False+ # 世代校验:等锁期间新回合可能已注册(register_stream_task+ # 是同步方法,不拿本锁)。迟到 → 放弃拆除,不写终态记录,+ # 否则新回合的 waiter 会把正常退出误报为暂停。+ if not self._is_current_runtime_epoch(session_id, target_epoch):+ logger.info(+ "[TeamManager] %slate pause superseded by newer round: session_id=%s",+ reason,+ session_id,+ )+ return False+logger.info("[TeamManager] %s pause team session runtime: session_id=%s",reason,@@ -2710,6 +2781,18 @@ class TeamManager:"[TeamManager] %s pause aborted: cancelled by cancel request, session_id=%s",reason, session_id,)+ # 世代校验:被 cancel 抢占时的让路拆除也可能迟到——+ # 若 Runner.pause 等待期间新回合已注册,这里的+ # stop/cleanup 会误杀新回合,改为放弃(cancel 自身+ # 会在校验中同步放弃)。+ if not self._is_current_runtime_epoch(session_id, target_epoch):+ logger.info(+ "[TeamManager] %slate pause abort superseded by "+ "newer round: session_id=%s",+ reason,+ session_id,+ )+ return Falseteam_name = self._resolve_session_team_name(session_id)if team_name:await self._stop_runner_team_runtime(diff --git a/tests/unit_tests/agentserver/test_team_runtime_epoch.py b/tests/unit_tests/agentserver/test_team_runtime_epoch.pynew file mode 100644index 0000000000..566e3eada9--- /dev/null+++ b/tests/unit_tests/agentserver/test_team_runtime_epoch.py@@ -0,0 +1,312 @@+# coding: utf-8+"""runtime 世代校验(epoch)单测:迟到拆除不得误杀新回合。++场景:cancel/pause 入口捕获世代号后卡在慢 await(如 30 人团队 Runner 清理+~53s),期间 relay-claw gate 超时放行、新"继续"回合完成注册(世代递增)。+迟到的拆除操作必须在破坏性步骤前放弃执行,且不写终态记录——否则新回合的+follow-up waiter 会把正常退出误报为取消/暂停。+"""+from __future__ import annotations++import asyncio+from unittest.mock import AsyncMock++import pytest++from jiuwenswarm.agents.harness.team.team_manager import Runner, TeamManager+++class _Harness(TeamManager):+ def set_active_runtime_for_test(self, session_id: str, team_name: str) -> None:+ self.commit_runtime_ready(session_id, team_name)++ def stub_no_live_team_agent(self) -> None:+ # cancel/pause 前置的 best-effort settle 在 team_agent=None 时直接跳过,+ # 避免单测触碰 Runner pool / checkpoint。+ self._resolve_live_team_agent = AsyncMock(return_value=None) # type: ignore[method-assign]++[email protected](autouse=True)+def _non_distributed_config(monkeypatch: pytest.MonkeyPatch) -> None:+ """单测统一走非分布式分支,prepare_runtime_activation 同步注册 pending。"""+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.team.team_manager.get_config",+ lambda: {},+ )+++def _manager() -> _Harness:+ mgr = _Harness()+ mgr.stub_no_live_team_agent()+ return mgr+++async def _register_round(mgr: _Harness, session_id: str, team_name: str) -> asyncio.Task:+ """模拟一个新回合的注册序列:prepare(bump epoch)→ 注册 stream task。"""+ await mgr.prepare_runtime_activation(session_id, team_name)+ task = asyncio.ensure_future(asyncio.sleep(3600))+ mgr.register_stream_task(session_id, task)+ return task+++async def _cancel_round_tasks(*tasks: asyncio.Task) -> None:+ for task in tasks:+ if not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+++async def test_epoch_bumps_once_per_round() -> None:+ """prepare 每回合递增一次;commit/register_stream_task 不再递增。"""+ mgr = _manager()+ assert mgr.get_session_runtime_epoch("sess-1") == 0+ await mgr.prepare_runtime_activation("sess-1", "team_t")+ assert mgr.get_session_runtime_epoch("sess-1") == 1+ mgr.commit_runtime_ready("sess-1", "team_t")+ task = asyncio.ensure_future(asyncio.sleep(0))+ mgr.register_stream_task("sess-1", task)+ assert mgr.get_session_runtime_epoch("sess-1") == 1+ await mgr.prepare_runtime_activation("sess-1", "team_t")+ assert mgr.get_session_runtime_epoch("sess-1") == 2+ await _cancel_round_tasks(task)+++async def test_late_cancel_superseded_keeps_new_round() -> None:+ """核心用例:cancel 卡在慢 settle 期间新回合注册 → cancel 放弃拆除。++ 生产事故时序:停止请求 → cancel 入口 → 卡在 HITL/Runner settle+ (数十秒)→ gate 超时放行 → 用户"继续"注册新回合 → cancel 迟到醒来。+ """+ mgr = _manager()+ mgr._settle_persisted_cancelled_permission_interrupt = AsyncMock() # type: ignore[method-assign]++ settle_entered = asyncio.Event()+ release_settle = asyncio.Event()++ async def slow_settle(*_args: object, **_kwargs: object) -> None:+ settle_entered.set()+ await release_settle.wait()++ mgr._settle_live_cancelled_permission_interrupt = slow_settle # type: ignore[method-assign]++ runner_stop_calls: list[str] = []++ async def fake_stop_runner(session_id: str, team_name: str, caller: str) -> bool:+ runner_stop_calls.append(caller)+ return True++ mgr._stop_runner_team_runtime = fake_stop_runner # type: ignore[method-assign]++ old_task = await _register_round(mgr, "sess-1", "team_t")++ cancel_task = asyncio.ensure_future(+ mgr.cancel_session_runtime("sess-1", reason="test")+ )+ await asyncio.wait_for(settle_entered.wait(), timeout=1.0)++ # 慢 settle 期间:新回合注册(relay-claw gate 放行后的"继续")+ new_task = await _register_round(mgr, "sess-1", "team_t")++ release_settle.set()+ assert await asyncio.wait_for(cancel_task, timeout=1.0) is False++ # 新回合存活:stream task 未被动过、无终态记录(waiter 不误报)+ assert new_task.done() is False+ assert new_task.cancelled() is False+ assert mgr.has_stream_task("sess-1") is True+ assert mgr.get_session_terminal_state("sess-1") is None+ # 未发生任何拆除:forced stop / lock 内拆除均未执行+ assert runner_stop_calls == []+ # 放弃路径必须清掉 cancel_requested,否则后续 pause 会被永久抑制+ assert "sess-1" not in mgr._cancel_requested+ mgr._settle_persisted_cancelled_permission_interrupt.assert_not_called()++ await _cancel_round_tasks(old_task, new_task)+++async def test_late_cancel_superseded_inside_lifecycle_lock() -> None:+ """校验点 2:cancel 等 lifecycle lock 期间新回合注册 → 进锁后放弃。"""+ mgr = _manager()+ mgr._settle_persisted_cancelled_permission_interrupt = AsyncMock() # type: ignore[method-assign]+ mgr.set_active_runtime_for_test("sess-1", "team_t")++ holder_locked = asyncio.Event()+ cancel_parked = asyncio.Event()+ new_round_registered = asyncio.Event()++ async def hold_lock() -> None:+ async with mgr._get_lifecycle_lock("sess-1"):+ holder_locked.set()+ await cancel_parked.wait()+ # cancel 已在 forced stop / 等锁途中:此刻注册新回合(bump epoch)+ await mgr.prepare_runtime_activation("sess-1", "team_t")+ new_task = asyncio.ensure_future(asyncio.sleep(3600))+ mgr.register_stream_task("sess-1", new_task)+ new_round_registered.set()++ async def fake_stop_runner(session_id: str, team_name: str, caller: str) -> bool:+ assert caller == "cancel: forced"+ cancel_parked.set()+ await new_round_registered.wait()+ return True++ mgr._stop_runner_team_runtime = fake_stop_runner # type: ignore[method-assign]++ holder = asyncio.ensure_future(hold_lock())+ await asyncio.wait_for(holder_locked.wait(), timeout=1.0)++ cancel_task = asyncio.ensure_future(+ mgr.cancel_session_runtime("sess-1", reason="test")+ )+ assert await asyncio.wait_for(cancel_task, timeout=1.0) is False+ await asyncio.wait_for(holder, timeout=1.0)++ # 迟到 cancel 进锁后放弃:不写终态记录,新回合 stream task 存活+ assert mgr.get_session_terminal_state("sess-1") is None+ assert mgr.has_stream_task("sess-1") is True+ stream_task = mgr._stream_tasks["sess-1"]+ assert stream_task.done() is False+ assert "sess-1" not in mgr._cancel_requested+ mgr._settle_persisted_cancelled_permission_interrupt.assert_not_called()++ await _cancel_round_tasks(stream_task)+++async def test_late_pause_superseded_keeps_new_round() -> None:+ """pause 等 lifecycle lock 期间新回合注册 → pause 放弃拆除、无终态记录。"""+ mgr = _manager()+ mgr.set_active_runtime_for_test("sess-1", "team_t")++ holder_locked = asyncio.Event()+ allow_holder_exit = asyncio.Event()++ async def hold_lock() -> asyncio.Task:+ async with mgr._get_lifecycle_lock("sess-1"):+ holder_locked.set()+ await allow_holder_exit.wait()+ # pause 已在等锁途中:注册新回合(bump epoch)+ return await _register_round(mgr, "sess-1", "team_t")++ runner_stop_calls: list[str] = []++ async def fake_stop_runner(session_id: str, team_name: str, caller: str) -> bool:+ runner_stop_calls.append(caller)+ return True++ mgr._stop_runner_team_runtime = fake_stop_runner # type: ignore[method-assign]++ holder = asyncio.ensure_future(hold_lock())+ await asyncio.wait_for(holder_locked.wait(), timeout=1.0)++ pause_task = asyncio.ensure_future(+ mgr.pause_session_runtime("sess-1", reason="test")+ )+ # 让 pause 运行到等锁挂起点+ await asyncio.sleep(0)+ allow_holder_exit.set()+ new_task = await asyncio.wait_for(holder, timeout=1.0)++ assert await asyncio.wait_for(pause_task, timeout=1.0) is False++ # 新回合存活、无 "paused" 终态记录、未触发任何拆除+ assert new_task.done() is False+ assert mgr.has_stream_task("sess-1") is True+ assert mgr.get_session_terminal_state("sess-1") is None+ assert runner_stop_calls == []++ await _cancel_round_tasks(new_task)+++async def test_pause_abort_skips_teardown_when_new_round_registered(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """pause 被 cancel 抢占:若新回合已注册,让路拆除同样放弃(由 cancel 决定)。"""+ mgr = _manager()+ mgr._settle_persisted_cancelled_permission_interrupt = AsyncMock() # type: ignore[method-assign]++ pause_entered = asyncio.Event()++ async def fake_pause_agent_team(**_kwargs: object) -> bool:+ pause_entered.set()+ await asyncio.sleep(3600)+ return True++ monkeypatch.setattr(+ Runner,+ "pause_agent_team",+ fake_pause_agent_team,+ )++ runner_stop_calls: list[str] = []++ async def fake_stop_runner(session_id: str, team_name: str, caller: str) -> bool:+ runner_stop_calls.append(caller)+ return True++ mgr._stop_runner_team_runtime = fake_stop_runner # type: ignore[method-assign]++ assert await mgr.prepare_runtime_activation("sess-1", "team_t") is None+ mgr.commit_runtime_ready("sess-1", "team_t")+ pause_task = asyncio.ensure_future(+ mgr.pause_session_runtime("sess-1", reason="test")+ )+ await asyncio.wait_for(pause_entered.wait(), timeout=1.0)++ # Runner.pause 等待期间新回合注册(不拿 lifecycle lock,与生产时序一致)+ new_task = await _register_round(mgr, "sess-1", "team_t")++ # cancel 到达:其入口捕获的已是新回合世代,preempt pause+ cancel_task = asyncio.ensure_future(+ mgr.cancel_session_runtime("sess-1", reason="test")+ )+ assert await asyncio.wait_for(cancel_task, timeout=1.0) is True+ assert await asyncio.wait_for(pause_task, timeout=1.0) is False++ # pause 的让路拆除被世代校验拦下(无 "pause aborted" stop);+ # cancel 作用于其到达时刻的目标(新回合),正常拆除并如实记录终态。+ assert "pause aborted" not in runner_stop_calls+ assert "cancel" in runner_stop_calls+ assert mgr.get_session_terminal_state("sess-1") == "cancelled"++ mgr._settle_persisted_cancelled_permission_interrupt.assert_awaited_once()+ await _cancel_round_tasks(new_task, pause_task)+++async def test_normal_cancel_still_tears_down() -> None:+ """回归:无新回合时世代校验不拦截,cancel 照常拆除并记录终态。"""+ mgr = _manager()+ mgr._settle_persisted_cancelled_permission_interrupt = AsyncMock() # type: ignore[method-assign]+ mgr.set_active_runtime_for_test("sess-1", "team_t")++ async def fake_stop_runner(session_id: str, team_name: str, caller: str) -> bool:+ return True++ mgr._stop_runner_team_runtime = fake_stop_runner # type: ignore[method-assign]++ assert await mgr.cancel_session_runtime("sess-1", reason="test") is True+ assert mgr.get_session_terminal_state("sess-1") == "cancelled"+++async def test_normal_pause_still_tears_down(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """回归:无新回合时 pause 照常拆除并记录终态。"""+ mgr = _manager()+ mgr.set_active_runtime_for_test("sess-2", "team_t")++ async def fake_pause_agent_team(**_kwargs: object) -> bool:+ return True++ monkeypatch.setattr(Runner, "pause_agent_team", fake_pause_agent_team)+ assert await mgr.pause_session_runtime("sess-2", reason="test") is True+ assert mgr.get_session_terminal_state("sess-2") == "paused"