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 time
from contextvars import ContextVar
from datetime import datetime, timezone
from functools import partial
from pathlib import Path
......@@ -46,6 +47,11 @@ from agentscope.memory import InMemoryMemory
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 = 0.2
......@@ -472,11 +478,12 @@ class AgentHub:
session_id, user_query[:100], file_url,
)
# 暂存路由上下文,供 _call_sub_agent 创建子 Agent 时注册 hook
self._current_route_ctx = dict(
# 暂存路由上下文(per-asyncio-Task,并发安全),
# 供 _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 {},
call_count=0,
)
))
session = self.session_service.get_or_create_session(
session_id=session_id,
......@@ -489,8 +496,6 @@ class AgentHub:
store=self.session_service.store,
max_rounds=20,
)
self._current_route_ctx["session_memory"] = memory
messages = memory.get_messages(max_rounds=10)
# 始终路由到 steward agent
......@@ -569,7 +574,7 @@ class AgentHub:
# 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束)
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 的"已委派"废话)
if call_count >= 1:
......@@ -688,7 +693,7 @@ class AgentHub:
)
# 为子 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"])
response = await sub_agent.reply(Msg("user", instruction, "user"))
......@@ -808,7 +813,7 @@ class AgentHub:
))]
)
# 新增:递增调用计数
ctx = getattr(self, "_current_route_ctx", None)
ctx = _route_context_var.get(None)
if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1
call_no = ctx["call_count"]
......
# Concurrent Session Isolation Fix
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Fix concurrent session cross-contamination where `AgentHub._current_route_ctx` (a singleton instance attribute) gets overwritten when multiple requests for different `group_contact_id` arrive concurrently, causing sub-agent replies to be sent to the wrong group chat.
**Architecture:** Replace shared mutable instance attribute `self._current_route_ctx` with Python `contextvars.ContextVar`, which provides per-asyncio-Task isolation. Each concurrent request gets its own routing context copy, preventing cross-session contamination.
**Root Cause:** `AgentHub` is a singleton. `self._current_route_ctx` is set at the start of `process_message()` (line 476), before the async `agent.reply()` call (line 545) that yields control. A concurrent request for a different session can overwrite the attribute during that yield, causing:
1. `_call_sub_agent()` reading the wrong `room_id` / `bot_id_mapping` → reply to wrong group
2. `call_count` contamination between sessions → one session's reply silently dropped
**Tech Stack:** Python `contextvars`, pytest-asyncio
---
### Task 0: Write the concurrent session test that exposes the bug (TDD)
**Files:**
- Modify: `tests/test_agent_hub.py:1108-1198`
#### ContextVar 导出
AgentHub 的 `_route_context_var` 需要在测试中直接使用。在 `agent_hub.py` 文件末尾(`close()` 方法之后)添加导出。
**Note:** This test will FAIL before the fix and PASS after. We write it first to demonstrate the bug.
**Test design:**
- Two concurrent `process_message` calls (different `session_id` / `room_id`)
- Model mock returns `tool_use` for idx=0 → triggers `call_sub_agent` tool, then yields with `asyncio.sleep(0.1)`
- During the yield, Session B starts, sets `_current_route_ctx` (overwriting Session A's value), then returns text directly (idx=1)
- Session A resumes: `call_sub_agent` tool executes → `_call_sub_agent` reads `_current_route_ctx` → **without fix**: gets Session B's `room_id` → sends sub-agent reply to wrong room
- Assertion: sub-agent reply for `MEETING_KEY` should include `"room_A"`
**Critical design note:** Uses a counter-based model mock (not `idx % 2`) to handle the fact that ReAct loop calls the model multiple times per session. idx=0 → tool_use (A's first call), idx=1 → text (B's first call), idx=2 → text (A's second call after tool returns). This avoids infinite ReAct loops from the counter pattern not matching iteration boundaries.
**Test details:**
```python
# ── 并发会话隔离测试 ──
class TestConcurrentSessions:
"""验证两个并发请求的 session 隔离(room_id 不串群)。"""
@pytest.mark.asyncio
async def test_concurrent_sessions_no_room_contamination(self):
"""并发会话:子Agent 回复不串群(room_id 隔离)。"""
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):
"""Counter-based: 0=tool_use(A yield), 1=text(B), 2=text(A after tool)."""
idx = model_call_count[0]
model_call_count[0] += 1
r = MagicMock()
if idx == 0:
r.content = [{"type": "tool_use", "id": "call_1", "name": "call_sub_agent",
"input": {"agent_code": MEETING_KEY, "instruction": "处理"}}]
await asyncio.sleep(0.1) # Yield: let B overwrite _current_route_ctx
elif idx == 1:
r.content = [{"type": "text", "text": "B完成"}]
elif idx == 2:
r.content = [{"type": "text", "text": "A完成"}]
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回复去的房间
a_sub_rooms = {room for room, name in post_replies if name == MEETING_KEY}
assert "room_A" in a_sub_rooms, (
f"A的子Agent回复未去 room_A,实际去了: {a_sub_rooms}\n"
f"全部 post_replies: {post_replies}"
)
- [ ] **Step 1: Write the concurrent test**
Copy the test class `TestConcurrentSessions` into `tests/test_agent_hub.py` (after the `TestMessageShielding` class).
- [ ] **Step 2: Run the test to verify it FAILS before the fix**
Run: `PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestConcurrentSessions -v --tb=long`
Expected: FAIL with assertion error showing rooms == {"room_B"} for room_A's agent.
Note: The test is timing-dependent by nature. If it happens to pass due to scheduling, run it 3-5 times. The fix in Task 1 is still needed regardless.
---
### Task 1: Replace `self._current_route_ctx` with `contextvars.ContextVar` in `AgentHub`
**Files:**
- Modify: `app/service/agent_hub.py`
This is the core fix. Three changes needed:
**Change 1 — Add import and module-level ContextVar** (at top of file, after other imports):
```python
from contextlib import contextmanager
from contextvars import ContextVar
# 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')
```
**Change 2 — In `process_message()` (line 476-478):**
Before:
```python
# 暂存路由上下文,供 _call_sub_agent 创建子 Agent 时注册 hook
self._current_route_ctx = dict(
room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
call_count=0,
)
```
After:
```python
# 暂存路由上下文(per-asyncio-Task,并发安全),
# 供 _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 {},
call_count=0,
))
```
**Change 3 — Remove `self._current_route_ctx["session_memory"]` assignment (line 492):**
Before:
```python
self._current_route_ctx["session_memory"] = memory
```
After: Simply delete this line — `session_memory` was stored in the context but never read from it anywhere. The local variable `memory` is used directly throughout `process_message()`.
**Change 4 — In `process_message()` line 572, reading call_count:**
Before:
```python
call_count = self._current_route_ctx.get("call_count", 0)
```
After:
```python
call_count = _route_context_var.get().get("call_count", 0)
```
**Change 5 — In `_call_sub_agent()` (line 691), reading routing context:**
Before:
```python
ctx = self._current_route_ctx
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
```
After:
```python
ctx = _route_context_var.get()
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
```
**Change 6 — In `call_sub_agent` closure inside `_make_call_sub_agent_tool()` (line 811), reading call_count:**
Before:
```python
ctx = getattr(self, "_current_route_ctx", None)
if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1
```
After:
```python
ctx = _route_context_var.get(None)
if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1
```
**Change 7 — Remove now-unused `self._current_route_ctx` references:**
No explicit cleanup needed — the ContextVar is scoped to the asyncio Task and auto-cleaned when the task completes.
**Self-review checklist:**
- [ ] Every read of `_current_route_ctx` in production code is replaced with `_route_context_var.get()`
- [ ] Every write to `_current_route_ctx` in production code is replaced with `_route_context_var.set()`
- [ ] Dead `session_memory` assignment removed
- [ ] **Step 1: Apply changes 1-7 to `app/service/agent_hub.py`**
- [ ] **Step 2: Quick syntax check**
Run: `python -c "import ast; ast.parse(open('app/service/agent_hub.py').read()); print('OK')"`
Expected: OK (no syntax errors)
---
### Task 2: Update existing tests that reference `_current_route_ctx`
**Files:**
- Modify: `tests/test_agent_hub.py`
All tests that directly set or read `hub._current_route_ctx` must be updated to use `_route_context_var` instead.
**Test 1 — `test_call_sub_agent_uses_sub_model` (lines 784-787):**
Before:
```python
hub._current_route_ctx = {
"room_id": "room_001", "user_id": "user_001", "bot_id_mapping": {},
}
```
After:
```python
from app.service.agent_hub import _route_context_var
token = _route_context_var.set({
"room_id": "room_001", "user_id": "user_001", "bot_id_mapping": {},
"call_count": 0,
})
```
Also add `_route_context_var.reset(token)` in a finally block:
```python
try:
with patch.object(ReActAgent, "__init__", new=capture_init):
await hub._call_sub_agent(MEETING_KEY, "test instruction")
finally:
_route_context_var.reset(token)
```
**Test 2 — `TestCallSubAgentCounter.test_call_count_initialized_in_route_ctx` (lines 990-997):**
This test is trivially testing that initialization of `call_count=0` works. Rewrite to use ContextVar:
```python
def test_call_count_initialized_in_route_ctx(self):
"""_route_context_var 初始化后 call_count 为 0。"""
token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
))
try:
ctx = _route_context_var.get()
assert ctx["call_count"] == 0
finally:
_route_context_var.reset(token)
```
**Test 3 — `TestCallSubAgentCounter.test_call_count_increments_in_tool` (lines 999-1013):**
Before:
```python
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
)
with patch.object(hub, '_call_sub_agent', ...):
tool = hub._make_call_sub_agent_tool()
await tool(...)
assert hub._current_route_ctx["call_count"] == 1
```
After:
```python
token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
))
try:
with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")):
tool = hub._make_call_sub_agent_tool()
await tool(agent_code=MEETING_KEY, instruction="测试指令")
ctx = _route_context_var.get()
assert ctx["call_count"] == 1
finally:
_route_context_var.reset(token)
```
**Test 4 — `TestSubAgentPostReply.test_call_sub_agent_sends_post_reply` (lines 1019-1047):**
Before:
```python
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
call_count=0,
)
```
After:
```python
token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
call_count=0,
))
try:
# ... existing test body ...
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
# ... assertions ...
finally:
_route_context_var.reset(token)
```
**Test 5 — `TestSubAgentPostReply.test_call_sub_agent_post_reply_failure_non_fatal` (lines 1049-1065):**
Same pattern as Test 4 — replace `hub._current_route_ctx = dict(...)` with ContextVar.
**Tests 6-8 — `test_main_agent_silent_when_call_count_is_1`, `_sends_when_0`, `_sends_when_2` (lines 1067-1106):**
These tests are testing `call_count != 1` comparison logic. Simplify to pure logic tests without hub:
```python
def test_main_agent_silent_when_call_count_is_1(self):
"""1 次 call_sub_agent 时,主 Agent 不发 post_reply。"""
call_count = 1
should_send = call_count != 1
assert should_send is False
# 实际 shoud_send 逻辑由 process_message line 586 的 `if call_count == 0:` 决定
def test_main_agent_sends_when_call_count_is_0(self):
"""0 次 call_sub_agent 时,主 Agent 正常发送。"""
call_count = 0
should_send = call_count == 0
assert should_send is True
def test_main_agent_sends_when_call_count_is_2(self):
"""2 次 call_sub_agent 时,主 Agent 不拦截(应调发言人)。"""
call_count = 2
assert call_count >= 1 # 触发静默分支
```
Note: `should_send = call_count != 1` was inaccurate — the actual process_message code uses `if call_count == 0:` at line 586, so `call_count >= 1` triggers silencing. The tests should reflect the actual logic.
- [ ] **Step 1: Apply test updates for Tests 1-8**
Update all 8 test locations in `tests/test_agent_hub.py`.
- [ ] **Step 2: Run all 3 groups of updated tests to verify they pass**
Run: `PYTHONPATH=. python -m pytest tests/test_agent_hub.py -v --tb=short -k "test_call_sub_agent_uses_sub_model or TestCallSubAgentCounter or TestSubAgentPostReply or test_main_agent_silent or test_main_agent_sends"`
Expected: All selected tests PASS.
---
### Task 3: Run full test suite and concurrent test
- [ ] **Step 1: Run the concurrent test**
Run: `PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestConcurrentSessions -v --tb=long`
Expected: PASS (no serialization assertion failure).
- [ ] **Step 2: Run the concurrent test 5 times to verify timing-stability**
Run: `for i in 1 2 3 4 5; do PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestConcurrentSessions -v --tb=short 2>&1 | tail -2; done`
Expected: All 5 runs PASS.
- [ ] **Step 3: Run all AgentHub and MessageGate tests**
Run: `PYTHONPATH=. python -m pytest tests/test_agent_hub.py tests/test_message_gate.py -v --tb=short`
Expected: 60/60 tests pass (53 AgentHub + 7 MessageGate).
- [ ] **Step 4: Run full test suite**
Run: `PYTHONPATH=. python -m pytest tests/ -v --tb=short`
Expected: All tests pass.
---
## Summary of Changes
| File | Change | Risk |
|------|--------|------|
| `app/service/agent_hub.py` | Add `_route_context_var` ContextVar; replace 4 reads/writes of `self._current_route_ctx` | Low — mechanical replacement, same API shape |
| `tests/test_agent_hub.py` | Add `TestConcurrentSessions` class; update 8 test locations to use ContextVar | Low — tests mirror production code change |
......@@ -7,7 +7,7 @@ from app.main import app as fastapi_app
# ── AgentHub 测试实例 ────────────────────────────────────────────
from app.config.settings import AgentConfig
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
......@@ -777,14 +777,13 @@ def test_agent_hub_has_sub_model_with_low_temperature():
@pytest.mark.asyncio
async def test_call_sub_agent_uses_sub_model():
"""_call_sub_agent 创建的 ReActAgent 应使用 sub_model 而非 main model。"""
from unittest.mock import patch, AsyncMock
from agentscope.agent import ReActAgent
hub = _make_test_hub()
# _call_sub_agent 内部访问 _current_route_ctx,需先设置
hub._current_route_ctx = {
_token = _route_context_var.set({
"room_id": "room_001", "user_id": "user_001", "bot_id_mapping": {},
}
"call_count": 0,
})
captured_model = None
real_init = ReActAgent.__init__
......@@ -796,8 +795,11 @@ async def test_call_sub_agent_uses_sub_model():
# 把 reply 替换为 AsyncMock 避免真实模型调用
self.reply = AsyncMock(return_value=MagicMock())
with patch.object(ReActAgent, "__init__", new=capture_init):
await hub._call_sub_agent(MEETING_KEY, "test instruction")
try:
with patch.object(ReActAgent, "__init__", new=capture_init):
await hub._call_sub_agent(MEETING_KEY, "test instruction")
finally:
_route_context_var.reset(_token)
# ReActAgent 应被创建,model 应该是 sub_model
assert captured_model is not None
......@@ -988,29 +990,31 @@ class TestCallSubAgentCounter:
"""测试 call_sub_agent 调用计数。"""
def test_call_count_initialized_in_route_ctx(self):
"""_current_route_ctx 初始化后 call_count 为 0。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=0,
)
assert hub._current_route_ctx["call_count"] == 0
"""_route_context_var 初始化后 call_count 为 0。"""
token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
))
try:
ctx = _route_context_var.get()
assert ctx["call_count"] == 0
finally:
_route_context_var.reset(token)
@pytest.mark.asyncio
async def test_call_count_increments_in_tool(self):
"""call_sub_agent 工具调用后计数器 +1。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={},
call_count=0,
)
# patch _call_sub_agent 避免真实创建 ReActAgent
with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")):
tool = hub._make_call_sub_agent_tool()
await tool(agent_code=MEETING_KEY, instruction="测试指令")
assert hub._current_route_ctx["call_count"] == 1
token = _route_context_var.set(dict(
room_id="r1", user_id="u1", bot_id_mapping={}, call_count=0,
))
try:
with patch.object(hub, '_call_sub_agent', new=AsyncMock(return_value="子Agent结果")):
tool = hub._make_call_sub_agent_tool()
await tool(agent_code=MEETING_KEY, instruction="测试指令")
ctx = _route_context_var.get()
assert ctx["call_count"] == 1
finally:
_route_context_var.reset(token)
class TestSubAgentPostReply:
......@@ -1020,22 +1024,25 @@ class TestSubAgentPostReply:
async def test_call_sub_agent_sends_post_reply(self):
"""_call_sub_agent 应通过 post_reply_hook 发送子 Agent 回复。"""
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"},
call_count=0,
)
))
# post_reply_hook.execute 是真实方法,用 AsyncMock(wraps=...) 包装以跟踪调用
mock_execute = AsyncMock(wraps=hub.post_reply_hook.execute)
mock_reply = _make_mock_model_reply("会议纪要已生成")
# 必须同时 patch sub_model 和 thinking_summary_model:
# thinking_summary_model 在 __init__ 时赋值为 sub_model 引用,
# post_reasoning hook 会调 _summarize_thinking → thinking_summary_model
with patch.object(hub, 'sub_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):
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
try:
# 必须同时 patch sub_model 和 thinking_summary_model:
# thinking_summary_model 在 __init__ 时赋值为 sub_model 引用,
# post_reasoning hook 会调 _summarize_thinking → thinking_summary_model
with patch.object(hub, 'sub_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):
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
finally:
_route_context_var.reset(token)
assert "会议纪要已生成" in result
......@@ -1050,60 +1057,39 @@ class TestSubAgentPostReply:
async def test_call_sub_agent_post_reply_failure_non_fatal(self):
"""post_reply 发送失败不影响子 Agent 返回结果。"""
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"},
call_count=0,
)
))
hub.post_reply_hook.execute = AsyncMock(side_effect=Exception("IM down"))
mock_reply = _make_mock_model_reply("会议纪要已生成")
with patch.object(hub, 'sub_model', new=mock_reply):
with patch.object(hub, 'thinking_summary_model', new=mock_reply):
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
try:
with patch.object(hub, 'sub_model', new=mock_reply):
with patch.object(hub, 'thinking_summary_model', new=mock_reply):
result = await hub._call_sub_agent(MEETING_KEY, "处理会议录音")
finally:
_route_context_var.reset(token)
# 结果正常返回
assert "会议纪要已生成" in result
def test_main_agent_silent_when_call_count_is_1(self):
"""1 次 call_sub_agent 时,主 Agent 不发 post_reply。"""
hub = _make_test_hub()
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 时跳过发送
call_count = 1
should_send = call_count != 1
assert should_send is False
def test_main_agent_sends_when_call_count_is_0(self):
"""0 次 call_sub_agent 时,主 Agent 正常发送。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
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
call_count = 0
should_send = call_count == 0
assert should_send is True
def test_main_agent_sends_when_call_count_is_2(self):
"""2+ 次 call_sub_agent 时,主 Agent 正常发综合回复。"""
hub = _make_test_hub()
hub._current_route_ctx = dict(
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
call_count = 2
assert call_count >= 1
import asyncio
......@@ -1195,3 +1181,63 @@ class TestMessageShielding:
"""call_count >= 2 → 同样不发送、不存 DB。"""
ctx = {"call_count": 3}
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!