Commit 2d5caff0 by sunqi02 Committed by 胡悦

fix: 修复并发会话串群 Bug — 用 ContextVar 替换 _current_route_ctx

AgentHub._current_route_ctx 是单例上的共享实例属性,并发请求在
agent.reply() yield 点后相互覆盖,导致子Agent 回复发到错误房间。

用 contextvars.ContextVar 替换,每个 asyncio Task 持有独立上下文。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 66604370
import logging import logging
import time import time
from contextvars import ContextVar
from datetime import datetime, timezone from datetime import datetime, timezone
from functools import partial from functools import partial
from pathlib import Path from pathlib import Path
...@@ -46,6 +47,11 @@ from agentscope.memory import InMemoryMemory ...@@ -46,6 +47,11 @@ from agentscope.memory import InMemoryMemory
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Per-request routing context, isolated per asyncio Task.
# Used by process_message, _call_sub_agent, and call_sub_agent tool closure
# to safely pass room_id/user_id/bot_id_mapping/call_count across async boundaries.
_route_context_var: ContextVar[dict] = ContextVar('route_context')
# sub_agent 专用低 temperature:调用子 Agent 处理确定性任务时使用更稳定的输出 # sub_agent 专用低 temperature:调用子 Agent 处理确定性任务时使用更稳定的输出
SUB_AGENT_TEMPERATURE = 0.2 SUB_AGENT_TEMPERATURE = 0.2
...@@ -472,11 +478,12 @@ class AgentHub: ...@@ -472,11 +478,12 @@ class AgentHub:
session_id, user_query[:100], file_url, session_id, user_query[:100], file_url,
) )
# 暂存路由上下文,供 _call_sub_agent 创建子 Agent 时注册 hook # 暂存路由上下文(per-asyncio-Task,并发安全),
self._current_route_ctx = dict( # 供 _call_sub_agent 创建子 Agent 时注册 hook 和发 IM
_route_context_var.set(dict(
room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {}, room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
call_count=0, call_count=0,
) ))
session = self.session_service.get_or_create_session( session = self.session_service.get_or_create_session(
session_id=session_id, session_id=session_id,
...@@ -489,8 +496,6 @@ class AgentHub: ...@@ -489,8 +496,6 @@ class AgentHub:
store=self.session_service.store, store=self.session_service.store,
max_rounds=20, max_rounds=20,
) )
self._current_route_ctx["session_memory"] = memory
messages = memory.get_messages(max_rounds=10) messages = memory.get_messages(max_rounds=10)
# 始终路由到 steward agent # 始终路由到 steward agent
...@@ -569,7 +574,7 @@ class AgentHub: ...@@ -569,7 +574,7 @@ class AgentHub:
# 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束) # 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束)
memory.add("assistant", response_raw, name=target_agent_name) memory.add("assistant", response_raw, name=target_agent_name)
call_count = self._current_route_ctx.get("call_count", 0) call_count = _route_context_var.get().get("call_count", 0)
# 3. call_count >= 1 时剔除最后一条 assistant(主Agent 的"已委派"废话) # 3. call_count >= 1 时剔除最后一条 assistant(主Agent 的"已委派"废话)
if call_count >= 1: if call_count >= 1:
...@@ -688,7 +693,7 @@ class AgentHub: ...@@ -688,7 +693,7 @@ class AgentHub:
) )
# 为子 Agent 注册 IM hook(post_reasoning → thinking 摘要) # 为子 Agent 注册 IM hook(post_reasoning → thinking 摘要)
ctx = self._current_route_ctx ctx = _route_context_var.get()
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"]) self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
response = await sub_agent.reply(Msg("user", instruction, "user")) response = await sub_agent.reply(Msg("user", instruction, "user"))
...@@ -808,7 +813,7 @@ class AgentHub: ...@@ -808,7 +813,7 @@ class AgentHub:
))] ))]
) )
# 新增:递增调用计数 # 新增:递增调用计数
ctx = getattr(self, "_current_route_ctx", None) ctx = _route_context_var.get(None)
if ctx: if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1 ctx["call_count"] = ctx.get("call_count", 0) + 1
call_no = ctx["call_count"] call_no = ctx["call_count"]
......
...@@ -7,7 +7,7 @@ from app.main import app as fastapi_app ...@@ -7,7 +7,7 @@ from app.main import app as fastapi_app
# ── AgentHub 测试实例 ──────────────────────────────────────────── # ── AgentHub 测试实例 ────────────────────────────────────────────
from app.config.settings import AgentConfig from app.config.settings import AgentConfig
from app.service.active_session_service import ActiveSessionService from app.service.active_session_service import ActiveSessionService
from app.service.agent_hub import AgentHub, AgentHubError from app.service.agent_hub import AgentHub, AgentHubError, _route_context_var
from app.service.memory import SessionMemory from app.service.memory import SessionMemory
...@@ -777,14 +777,13 @@ def test_agent_hub_has_sub_model_with_low_temperature(): ...@@ -777,14 +777,13 @@ def test_agent_hub_has_sub_model_with_low_temperature():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_call_sub_agent_uses_sub_model(): async def test_call_sub_agent_uses_sub_model():
"""_call_sub_agent 创建的 ReActAgent 应使用 sub_model 而非 main model。""" """_call_sub_agent 创建的 ReActAgent 应使用 sub_model 而非 main model。"""
from unittest.mock import patch, AsyncMock
from agentscope.agent import ReActAgent from agentscope.agent import ReActAgent
hub = _make_test_hub() hub = _make_test_hub()
# _call_sub_agent 内部访问 _current_route_ctx,需先设置 _token = _route_context_var.set({
hub._current_route_ctx = {
"room_id": "room_001", "user_id": "user_001", "bot_id_mapping": {}, "room_id": "room_001", "user_id": "user_001", "bot_id_mapping": {},
} "call_count": 0,
})
captured_model = None captured_model = None
real_init = ReActAgent.__init__ real_init = ReActAgent.__init__
...@@ -796,8 +795,11 @@ async def test_call_sub_agent_uses_sub_model(): ...@@ -796,8 +795,11 @@ async def test_call_sub_agent_uses_sub_model():
# 把 reply 替换为 AsyncMock 避免真实模型调用 # 把 reply 替换为 AsyncMock 避免真实模型调用
self.reply = AsyncMock(return_value=MagicMock()) self.reply = AsyncMock(return_value=MagicMock())
try:
with patch.object(ReActAgent, "__init__", new=capture_init): with patch.object(ReActAgent, "__init__", new=capture_init):
await hub._call_sub_agent(MEETING_KEY, "test instruction") await hub._call_sub_agent(MEETING_KEY, "test instruction")
finally:
_route_context_var.reset(_token)
# ReActAgent 应被创建,model 应该是 sub_model # ReActAgent 应被创建,model 应该是 sub_model
assert captured_model is not None assert captured_model is not None
...@@ -988,29 +990,31 @@ class TestCallSubAgentCounter: ...@@ -988,29 +990,31 @@ class TestCallSubAgentCounter:
"""测试 call_sub_agent 调用计数。""" """测试 call_sub_agent 调用计数。"""
def test_call_count_initialized_in_route_ctx(self): def test_call_count_initialized_in_route_ctx(self):
"""_current_route_ctx 初始化后 call_count 为 0。""" """_route_context_var 初始化后 call_count 为 0。"""
hub = _make_test_hub() token = _route_context_var.set(dict(
hub._current_route_ctx = dict( room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
room_id="r1", user_id="u1", bot_id_mapping={}, ))
call_count=0, try:
) ctx = _route_context_var.get()
assert hub._current_route_ctx["call_count"] == 0 assert ctx["call_count"] == 0
finally:
_route_context_var.reset(token)
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_call_count_increments_in_tool(self): async def test_call_count_increments_in_tool(self):
"""call_sub_agent 工具调用后计数器 +1。""" """call_sub_agent 工具调用后计数器 +1。"""
hub = _make_test_hub() hub = _make_test_hub()
hub._current_route_ctx = dict( token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={}, room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
call_count=0, ))
) try:
# patch _call_sub_agent 避免真实创建 ReActAgent
with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")): with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")):
tool = hub._make_call_sub_agent_tool() tool = hub._make_call_sub_agent_tool()
await tool(agent_code=MEETING_KEY, instruction="测试指令") await tool(agent_code=MEETING_KEY, instruction="测试指令")
ctx = _route_context_var.get()
assert hub._current_route_ctx["call_count"] == 1 assert ctx["call_count"] == 1
finally:
_route_context_var.reset(token)
class TestSubAgentPostReply: class TestSubAgentPostReply:
...@@ -1020,15 +1024,16 @@ class TestSubAgentPostReply: ...@@ -1020,15 +1024,16 @@ class TestSubAgentPostReply:
async def test_call_sub_agent_sends_post_reply(self): async def test_call_sub_agent_sends_post_reply(self):
"""_call_sub_agent 应通过 post_reply_hook 发送子 Agent 回复。""" """_call_sub_agent 应通过 post_reply_hook 发送子 Agent 回复。"""
hub = _make_test_hub() hub = _make_test_hub()
hub._current_route_ctx = dict( token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"}, room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
call_count=0, call_count=0,
) ))
# post_reply_hook.execute 是真实方法,用 AsyncMock(wraps=...) 包装以跟踪调用 # post_reply_hook.execute 是真实方法,用 AsyncMock(wraps=...) 包装以跟踪调用
mock_execute = AsyncMock(wraps=hub.post_reply_hook.execute) mock_execute = AsyncMock(wraps=hub.post_reply_hook.execute)
mock_reply = _make_mock_model_reply("会议纪要已生成") mock_reply = _make_mock_model_reply("会议纪要已生成")
try:
# 必须同时 patch sub_model 和 thinking_summary_model: # 必须同时 patch sub_model 和 thinking_summary_model:
# thinking_summary_model 在 __init__ 时赋值为 sub_model 引用, # thinking_summary_model 在 __init__ 时赋值为 sub_model 引用,
# post_reasoning hook 会调 _summarize_thinking → thinking_summary_model # post_reasoning hook 会调 _summarize_thinking → thinking_summary_model
...@@ -1036,6 +1041,8 @@ class TestSubAgentPostReply: ...@@ -1036,6 +1041,8 @@ class TestSubAgentPostReply:
with patch.object(hub, 'thinking_summary_model', new=mock_reply): with patch.object(hub, 'thinking_summary_model', new=mock_reply):
with patch.object(hub.post_reply_hook, 'execute', new=mock_execute): with patch.object(hub.post_reply_hook, 'execute', new=mock_execute):
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音") result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
finally:
_route_context_var.reset(token)
assert "会议纪要已生成" in result assert "会议纪要已生成" in result
...@@ -1050,60 +1057,39 @@ class TestSubAgentPostReply: ...@@ -1050,60 +1057,39 @@ class TestSubAgentPostReply:
async def test_call_sub_agent_post_reply_failure_non_fatal(self): async def test_call_sub_agent_post_reply_failure_non_fatal(self):
"""post_reply 发送失败不影响子 Agent 返回结果。""" """post_reply 发送失败不影响子 Agent 返回结果。"""
hub = _make_test_hub() hub = _make_test_hub()
hub._current_route_ctx = dict( token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"}, room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
call_count=0, call_count=0,
) ))
hub.post_reply_hook.execute = AsyncMock(side_effect=Exception("IM down")) hub.post_reply_hook.execute = AsyncMock(side_effect=Exception("IM down"))
mock_reply = _make_mock_model_reply("会议纪要已生成") mock_reply = _make_mock_model_reply("会议纪要已生成")
try:
with patch.object(hub, 'sub_model', new=mock_reply): with patch.object(hub, 'sub_model', new=mock_reply):
with patch.object(hub, 'thinking_summary_model', new=mock_reply): with patch.object(hub, 'thinking_summary_model', new=mock_reply):
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音") result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
finally:
_route_context_var.reset(token)
# 结果正常返回 # 结果正常返回
assert "会议纪要已生成" in result assert "会议纪要已生成" in result
def test_main_agent_silent_when_call_count_is_1(self): def test_main_agent_silent_when_call_count_is_1(self):
"""1 次 call_sub_agent 时,主 Agent 不发 post_reply。""" """1 次 call_sub_agent 时,主 Agent 不发 post_reply。"""
hub = _make_test_hub() call_count = 1
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=1,
)
# 模拟 process_message 结尾的判断逻辑
call_count = hub._current_route_ctx.get("call_count", 0)
assert call_count == 1
# count == 1 时跳过发送
should_send = call_count != 1 should_send = call_count != 1
assert should_send is False assert should_send is False
def test_main_agent_sends_when_call_count_is_0(self): def test_main_agent_sends_when_call_count_is_0(self):
"""0 次 call_sub_agent 时,主 Agent 正常发送。""" """0 次 call_sub_agent 时,主 Agent 正常发送。"""
hub = _make_test_hub() call_count = 0
hub._current_route_ctx = dict( should_send = call_count == 0
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=0,
)
call_count = hub._current_route_ctx.get("call_count", 0)
assert call_count == 0
should_send = call_count != 1
assert should_send is True assert should_send is True
def test_main_agent_sends_when_call_count_is_2(self): def test_main_agent_sends_when_call_count_is_2(self):
"""2+ 次 call_sub_agent 时,主 Agent 正常发综合回复。""" """2+ 次 call_sub_agent 时,主 Agent 正常发综合回复。"""
hub = _make_test_hub() call_count = 2
hub._current_route_ctx = dict( assert call_count >= 1
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=2,
)
call_count = hub._current_route_ctx.get("call_count", 0)
assert call_count == 2
should_send = call_count != 1
assert should_send is True
import asyncio import asyncio
...@@ -1195,3 +1181,63 @@ class TestMessageShielding: ...@@ -1195,3 +1181,63 @@ class TestMessageShielding:
"""call_count >= 2 → 同样不发送、不存 DB。""" """call_count >= 2 → 同样不发送、不存 DB。"""
ctx = {"call_count": 3} ctx = {"call_count": 3}
assert ctx["call_count"] >= 1 assert ctx["call_count"] >= 1
# ── 并发会话隔离测试 ──
class TestConcurrentSessions:
"""并发会话隔离:验证子Agent room_id 不串群(回归验证 race condition)。"""
@pytest.mark.asyncio
async def test_concurrent_sessions_no_room_contamination(self):
"""并发会话:两个会话都触发 call_sub_Agent,回复应发到各自房间。"""
hub = test_hub
post_replies = []
model_call_count = [0]
mock_sub = _make_mock_model_reply("子Agent处理结果")
async def track(data):
post_replies.append((data["room_id"], data["agent_name"]))
async def model_side_effect(*args, **kwargs):
"""Both sessions return tool_use (idx<2), then text (idx>=2).
First call yields to let the other session overwrite _current_route_ctx."""
idx = model_call_count[0]
model_call_count[0] += 1
r = MagicMock()
if idx < 2: # First model call for BOTH sessions: both trigger call_sub_agent
r.content = [{"type": "tool_use", "id": "call_1", "name": "call_sub_agent",
"input": {"agent_code": MEETING_KEY, "instruction": "处理"}}]
if idx == 0:
await asyncio.sleep(0.1) # Yield: let other session overwrite ctx
else: # Second model call for BOTH sessions: text reply
r.content = [{"type": "text", "text": "完成"}]
return r
model_mock = AsyncMock(side_effect=model_side_effect)
model_mock.stream = False
with patch.object(hub, 'model', new=model_mock):
with patch.object(hub, 'sub_model', new=mock_sub):
with patch.object(hub, 'thinking_summary_model', new=mock_sub):
with patch.object(hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
with patch.object(hub.post_reply_hook, 'execute', new=AsyncMock(side_effect=track)):
await asyncio.gather(
hub.process_message(
session_id="sess_A", room_id="room_A",
user_id="u1", user_query="Q1",
),
hub.process_message(
session_id="sess_B", room_id="room_B",
user_id="u2", user_query="Q2",
),
)
# 验证子Agent回复的房间隔离
# Without isolation: 两个子Agent 回复都去同一个房间(最后一个设置 ctx 的房间)
# With isolation: 各去各的房间
sub_agent_rooms = {room for room, name in post_replies if name == MEETING_KEY}
assert len(sub_agent_rooms) >= 2, (
f"两个子Agent 回复发到同一房间!存在串群 Bug: {sub_agent_rooms}\n"
f"全部 post_replies: {post_replies}"
)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!