Commit 439b92de by sunqi02 Committed by 胡悦

fix: SessionBuffer 入锁 + AgentHub 移出锁,消除并发覆盖风险

- MessageGate 新增 _extract_query_and_file_url() 静态方法
- _handle_actionable 签名改为接收预提取的 (query, file_url)
- evaluate() 锁内 clear_pending,锁外调 AgentHub
- MessageGate 新增 append_messages(),per-session 锁保护 buffer 追加
- endpoint 改用 append_messages() 替代裸 SessionBuffer.append()
- 更新 MessageGate 测试适配锁重构 + LLM 临时放行
- 新增 4 个 _extract_query_and_file_url 单元测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 2f397726
...@@ -127,13 +127,10 @@ async def chat( ...@@ -127,13 +127,10 @@ async def chat(
if steward_bot_id: if steward_bot_id:
bot_id_mapping[MOUTH_AGENT_CODE] = steward_bot_id bot_id_mapping[MOUTH_AGENT_CODE] = steward_bot_id
# 4. 追加消息到 buffer(在 BackgroundTask 之外,确保锁外追加) # 4. 追加消息到 buffer(在 MessageGate per-session 锁内,确保并发安全)
from app.service.session_buffer import SessionBuffer await message_gate.append_messages(
from app.infrastructure.session_store import SessionStore session_id, [m.model_dump() for m in request.messages]
store = SessionStore() )
buffer = SessionBuffer(store, session_id, session_service=agent_hub.session_service)
for msg in request.messages:
buffer.append(msg.model_dump())
# 4.5 入口日志:记录本次请求的概要(不打印完整 payload,避免敏感信息泄露) # 4.5 入口日志:记录本次请求的概要(不打印完整 payload,避免敏感信息泄露)
text_preview = (query[:80] + "…") if len(query) > 80 else query text_preview = (query[:80] + "…") if len(query) > 80 else query
......
...@@ -70,6 +70,17 @@ class MessageGate: ...@@ -70,6 +70,17 @@ class MessageGate:
self._session_locks[session_id] = asyncio.Lock() self._session_locks[session_id] = asyncio.Lock()
return self._session_locks[session_id] return self._session_locks[session_id]
async def append_messages(self, session_id: str, messages: List[Dict[str, Any]]) -> None:
"""追加消息到 session buffer,使用 per-session 锁保证并发安全。"""
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore
async with self._get_lock(session_id):
store = SessionStore()
buffer = SessionBuffer(store, session_id, session_service=self.session_service)
for msg in messages:
buffer.append(msg)
async def evaluate( async def evaluate(
self, self,
session_id: str, session_id: str,
...@@ -119,6 +130,8 @@ class MessageGate: ...@@ -119,6 +130,8 @@ class MessageGate:
self._running_tasks[session_id] = asyncio.current_task() self._running_tasks[session_id] = asyncio.current_task()
try: try:
actionable_args = None # (query, file_url) for lock-external AgentHub call
async with lock: async with lock:
# 调试:记录锁获取时的 KV 状态 # 调试:记录锁获取时的 KV 状态
_kv_data = store.get(session_id) or {} _kv_data = store.get(session_id) or {}
...@@ -156,16 +169,22 @@ class MessageGate: ...@@ -156,16 +169,22 @@ class MessageGate:
buffer.clear_pending() buffer.clear_pending()
return return
# pass # pass: 锁内提取 query/file_url + clear_pending
query, file_url = self._extract_query_and_file_url(pending)
buffer.clear_pending()
actionable_args = (query, file_url)
# ── 锁外:AgentHub ReAct 循环不持锁 ──
if actionable_args:
query, file_url = actionable_args
await self._handle_actionable( await self._handle_actionable(
session_id=session_id, session_id=session_id,
room_id=room_id, room_id=room_id,
user_id=user_id, user_id=user_id,
decision=decision, query=query,
pending=pending, file_url=file_url,
bot_id_mapping=bot_id_mapping, bot_id_mapping=bot_id_mapping,
) )
buffer.clear_pending()
finally: finally:
self._running_tasks.pop(session_id, None) self._running_tasks.pop(session_id, None)
...@@ -173,31 +192,8 @@ class MessageGate: ...@@ -173,31 +192,8 @@ class MessageGate:
self, self,
pending: List[Dict[str, Any]], pending: List[Dict[str, Any]],
) -> "GateDecision": ) -> "GateDecision":
"""调 LLM 判断当前消息是否需要激活助手。无历史上下文,只看当前消息。 """直接放行所有消息,跳过 LLM 意图分类。"""
Returns:
GateDecision with intent="chat" or "pass"
"""
merged_text = self._merge_text_from_pending(pending)
if not merged_text:
return GateDecision(intent="chat")
prompt = (
"你是助手激活识别器。判断当前消息是否需要AI助手响应。\n"
"- chat:打招呼、道谢、确认收到、纯社交寒暄、群友间对话 —— 助手沉默\n"
"- pass:提问、命令、文件处理、提到某Agent名称、需要协助 —— 激活助手\n"
"\n只输出 \"chat\" 或 \"pass\"。\n"
"\n当前消息:\n" + merged_text
)
messages = [{"role": "user", "content": prompt}]
response = await self.model(messages=messages)
text = self._extract_text(response).strip().lower()
logger.debug("[MessageGate] activation response: %s", text)
if text == "pass":
return GateDecision(intent="pass") return GateDecision(intent="pass")
return GateDecision(intent="chat") # 兜底默认:chat
async def _handle_chat( async def _handle_chat(
self, self,
...@@ -240,6 +236,35 @@ class MessageGate: ...@@ -240,6 +236,35 @@ class MessageGate:
parts.append(f"[文件: {mc}]") parts.append(f"[文件: {mc}]")
return "\n".join(parts) if parts else "" return "\n".join(parts) if parts else ""
@staticmethod
def _extract_query_and_file_url(
pending: List[Dict[str, Any]],
) -> tuple:
"""从 pending 消息中提取 query 文本和 file_url。
在锁内调用,返回 (query, file_url),AgentHub 在锁外使用。
"""
query = MessageGate._merge_text_from_pending(pending)
# 安全网:从 text 消息中提取 URL,补齐可能丢弃的链接
URL_RE = re.compile(r'https?://[^\s<>"{}|\\^`\[\]]+')
for m in pending:
if m.get("msg_type") != "text":
continue
mc = m.get("msg_content", "")
for url in URL_RE.findall(mc):
if url not in query:
query = f"{query}\n{url}"
# 提取 file_url(取第一个非 text 消息的 URL)
file_url = None
for m in pending:
if m.get("msg_type") != "text" and m.get("msg_content"):
file_url = m["msg_content"]
break
return query, file_url
async def _handle_casual( async def _handle_casual(
self, self,
session_id: str, session_id: str,
...@@ -351,35 +376,15 @@ class MessageGate: ...@@ -351,35 +376,15 @@ class MessageGate:
session_id: str, session_id: str,
room_id: str, room_id: str,
user_id: str, user_id: str,
decision: "GateDecision", query: str,
pending: List[Dict[str, Any]], file_url: Optional[str],
bot_id_mapping: Dict[str, str], bot_id_mapping: Dict[str, str],
) -> None: ) -> None:
"""pass 分支:分发到 AgentHub。""" """pass 分支:分发到 AgentHub。query/file_url 由调用方在锁内预先提取。"""
query = self._merge_text_from_pending(pending)
if not query: if not query:
logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id) logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
return return
# 安全网:从 text 消息中提取 URL,补齐 rewritten_query 可能丢弃的链接
# 只补 text 类型(用户主动写的 URL),不补 file/image 类型的历史残留链接
URL_RE = re.compile(r'https?://[^\s<>"{}|\\^`\[\]]+')
for m in pending:
if m.get("msg_type") != "text":
continue
mc = m.get("msg_content", "")
for url in URL_RE.findall(mc):
if url not in query:
query = f"{query}\n{url}"
# 提取 file_url(取第一个非 text 消息的 URL)
file_url = None
for m in pending:
if m.get("msg_type") != "text" and m.get("msg_content"):
file_url = m["msg_content"]
break
try: try:
await self.agent_hub.process_message( await self.agent_hub.process_message(
session_id=session_id, session_id=session_id,
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
"sender_id": "", "sender_id": "",
"sender_name": "孙奇", "sender_name": "孙奇",
"msg_type": "text", "msg_type": "text",
"msg_content": "课程涵盖哪些内容?", "msg_content": "我想知道问界延保的价格",
"payload": {} "payload": {}
} }
] ]
......
...@@ -27,7 +27,7 @@ def test_gate_decision_only_intent(): ...@@ -27,7 +27,7 @@ def test_gate_decision_only_intent():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_classify_returns_chat_for_empty_pending(): async def test_classify_returns_chat_for_empty_pending():
"""空 pending → 返回 chat。""" """空 pending → 当前临时直接放行,返回 pass。"""
gate = MessageGate( gate = MessageGate(
config_loader=MagicMock(), config_loader=MagicMock(),
session_service=MagicMock(), session_service=MagicMock(),
...@@ -37,50 +37,23 @@ async def test_classify_returns_chat_for_empty_pending(): ...@@ -37,50 +37,23 @@ async def test_classify_returns_chat_for_empty_pending():
model=MagicMock(), model=MagicMock(),
) )
decision = await gate._classify_and_rewrite(pending=[]) decision = await gate._classify_and_rewrite(pending=[])
assert decision.intent == "chat"
@pytest.mark.asyncio
async def test_classify_activation_model_called():
"""LLM 返回 'pass' → GateDecision intent='pass'。"""
mock_model = AsyncMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "pass"}]
mock_model.return_value = mock_model_response
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=mock_model,
)
pending = [{"msg_type": "text", "msg_content": "帮我整理会议纪要"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "pass" assert decision.intent == "pass"
mock_model.assert_called_once()
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_classify_activation_returns_chat_by_default(): async def test_classify_activation_returns_chat_by_default():
"""LLM 返回未知内容 → 兜底 chat。""" """直接放行模式:返回 pass(临时跳过 LLM 分类)。"""
mock_model = AsyncMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "hello"}]
mock_model.return_value = mock_model_response
gate = MessageGate( gate = MessageGate(
config_loader=MagicMock(), config_loader=MagicMock(),
session_service=MagicMock(), session_service=MagicMock(),
post_reply_hook=MagicMock(), post_reply_hook=MagicMock(),
agent_hub=MagicMock(), agent_hub=MagicMock(),
main_agent_key="11", main_agent_key="11",
model=mock_model, model=MagicMock(),
) )
pending = [{"msg_type": "text", "msg_content": "谢谢大家"}] pending = [{"msg_type": "text", "msg_content": "谢谢大家"}]
decision = await gate._classify_and_rewrite(pending=pending) decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "chat" assert decision.intent == "pass"
@pytest.mark.asyncio @pytest.mark.asyncio
...@@ -119,7 +92,7 @@ async def test_handle_chat_adds_user_message_to_history(): ...@@ -119,7 +92,7 @@ async def test_handle_chat_adds_user_message_to_history():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_handle_actionable_calls_agent_hub(): async def test_handle_actionable_calls_agent_hub():
"""_handle_actionable 调用 agent_hub.process_message。""" """_handle_actionable 用预提取的 query/file_url 调用 agent_hub.process_message。"""
mock_agent_hub = MagicMock() mock_agent_hub = MagicMock()
mock_agent_hub.process_message = AsyncMock() mock_agent_hub.process_message = AsyncMock()
...@@ -131,16 +104,60 @@ async def test_handle_actionable_calls_agent_hub(): ...@@ -131,16 +104,60 @@ async def test_handle_actionable_calls_agent_hub():
main_agent_key="11", main_agent_key="11",
model=MagicMock(), model=MagicMock(),
) )
decision = GateDecision(intent="pass")
pending = [{"msg_type": "text", "msg_content": "创建任务"}]
await gate._handle_actionable( await gate._handle_actionable(
session_id="test-session", session_id="test-session",
room_id="room-1", room_id="room-1",
user_id="user-1", user_id="user-1",
decision=decision, query="创建任务",
pending=pending, file_url=None,
bot_id_mapping={"11": "bot_main"}, bot_id_mapping={"11": "bot_main"},
) )
mock_agent_hub.process_message.assert_called_once() mock_agent_hub.process_message.assert_called_once()
call_kwargs = mock_agent_hub.process_message.call_args.kwargs
assert call_kwargs["user_query"] == "创建任务"
assert call_kwargs["file_url"] is None
# ── _extract_query_and_file_url 单元测试 ──
def test_extract_query_and_file_url_text_only():
"""仅包含文本消息时,提取 query 且 file_url 为 None。"""
from app.service.message_gate import MessageGate
pending = [{"msg_type": "text", "msg_content": "帮我整理纪要"}]
query, file_url = MessageGate._extract_query_and_file_url(pending)
assert query == "帮我整理纪要"
assert file_url is None
def test_extract_query_and_file_url_with_file():
"""混合文本+文件消息时,提取 query 和 file_url。"""
from app.service.message_gate import MessageGate
pending = [
{"msg_type": "text", "msg_content": "分析这份报表"},
{"msg_type": "file", "msg_content": "https://oss.example.com/report.xlsx"},
]
query, file_url = MessageGate._extract_query_and_file_url(pending)
assert "分析这份报表" in query
assert file_url == "https://oss.example.com/report.xlsx"
def test_extract_query_and_file_url_append_url():
"""文本中已含 URL 时,不重复追加。"""
from app.service.message_gate import MessageGate
pending = [
{"msg_type": "text", "msg_content": "看下这个 https://example.com/doc"},
]
query, file_url = MessageGate._extract_query_and_file_url(pending)
assert "https://example.com/doc" in query
assert query.count("https://example.com/doc") == 1
assert file_url is None
def test_extract_query_and_file_url_empty():
"""空 pending 返回空 query。"""
from app.service.message_gate import MessageGate
query, file_url = MessageGate._extract_query_and_file_url([])
assert query == ""
assert file_url is None
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!