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:
-
_call_sub_agent()reading the wrongroom_id/bot_id_mapping→ reply to wrong group -
call_countcontamination 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_messagecalls (differentsession_id/room_id) - Model mock returns
tool_usefor idx=0 → triggerscall_sub_agenttool, then yields withasyncio.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_agenttool executes →_call_sub_agentreads_current_route_ctx→ without fix: gets Session B'sroom_id→ sends sub-agent reply to wrong room - Assertion: sub-agent reply for
MEETING_KEYshould 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:
# ── 并发会话隔离测试 ──
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:
# 暂存路由上下文,供 _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:
# 暂存路由上下文(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:
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:
call_count = self._current_route_ctx.get("call_count", 0)
After:
call_count = _route_context_var.get().get("call_count", 0)
Change 5 — In _call_sub_agent() (line 691), reading routing context:
Before:
ctx = self._current_route_ctx
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
After:
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:
ctx = getattr(self, "_current_route_ctx", None)
if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1
After:
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_ctxin production code is replaced with_route_context_var.get() -
Every write to
_current_route_ctxin production code is replaced with_route_context_var.set() Dead
session_memoryassignment removedStep 1: Apply changes 1-7 to
app/service/agent_hub.pyStep 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:
hub._current_route_ctx = {
"room_id": "room_001", "user_id": "user_001", "bot_id_mapping": {},
}
After:
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:
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:
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:
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:
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:
hub._current_route_ctx = dict(
room_id="r1", user_id="u1", bot_id_mapping={MEETING_KEY: "bot_meeting"},
call_count=0,
)
After:
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:
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 |