Commit 4ebc7c86 by sunqi02

refactor(message-gate): fix review issues - remove race condition, dead code, unused imports

- Remove _current_bot_id_mapping instance variable, pass bot_id_mapping as parameter instead (race condition fix)
- Remove dead _process_message_async function from agent_hub.py
- Remove unused SessionMemory import in _classify_and_rewrite
- Update close() to cancel running tasks before clearing
- Remove unused messages parameter from evaluate()
- Remove dead _dispatch_to_agent_hub mock in test

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 5d405ad0
...@@ -137,34 +137,6 @@ async def chat( ...@@ -137,34 +137,6 @@ async def chat(
return {"status": "ok", "session_id": session_id} return {"status": "ok", "session_id": session_id}
async def _process_message_async(
agent_hub: AgentHub,
session_id: str,
room_id: str,
user_id: str,
user_query: str,
file_url: Optional[str],
allowed_agent_codes: Optional[list],
bot_id_mapping: Optional[dict] = None,
):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try:
await agent_hub.process_message(
session_id=session_id,
room_id=room_id,
user_id=user_id,
user_query=user_query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
bot_id_mapping=bot_id_mapping,
)
except Exception:
logger.exception(
"Agent 后台处理失败: session=%s user=%s query=%s",
session_id, user_id, user_query[:50],
)
async def _process_message_async_via_gate( async def _process_message_async_via_gate(
agent_hub: AgentHub, agent_hub: AgentHub,
message_gate: MessageGate, message_gate: MessageGate,
...@@ -181,7 +153,6 @@ async def _process_message_async_via_gate( ...@@ -181,7 +153,6 @@ async def _process_message_async_via_gate(
room_id=room_id, room_id=room_id,
user_id=user_id, user_id=user_id,
bot_id_mapping=bot_id_mapping or {}, bot_id_mapping=bot_id_mapping or {},
messages=messages,
) )
except Exception: except Exception:
logger.exception("MessageGate 评估失败,尝试兜底") logger.exception("MessageGate 评估失败,尝试兜底")
......
...@@ -46,8 +46,6 @@ class MessageGate: ...@@ -46,8 +46,6 @@ class MessageGate:
# 运行时状态 # 运行时状态
self._session_locks: Dict[str, asyncio.Lock] = {} self._session_locks: Dict[str, asyncio.Lock] = {}
self._running_tasks: Dict[str, asyncio.Task] = {} self._running_tasks: Dict[str, asyncio.Task] = {}
# 每次 evaluate 调用时由 endpoint 注入的 bot_id_mapping
self._current_bot_id_mapping: Dict[str, str] = {}
# 模型:优先使用注入的(测试场景),否则从配置加载 # 模型:优先使用注入的(测试场景),否则从配置加载
if model is not None: if model is not None:
...@@ -76,7 +74,6 @@ class MessageGate: ...@@ -76,7 +74,6 @@ class MessageGate:
room_id: str, room_id: str,
user_id: str, user_id: str,
bot_id_mapping: Dict[str, str], bot_id_mapping: Dict[str, str],
messages: List[Dict[str, Any]] = None,
wait_seconds: float = 6.0, wait_seconds: float = 6.0,
) -> None: ) -> None:
"""评估入口:等待、分类、重写、分发。 """评估入口:等待、分类、重写、分发。
...@@ -86,12 +83,8 @@ class MessageGate: ...@@ -86,12 +83,8 @@ class MessageGate:
room_id: 房间 ID room_id: 房间 ID
user_id: 用户 ID user_id: 用户 ID
bot_id_mapping: 由 endpoint 注入的 agent_key → bot_id 映射 bot_id_mapping: 由 endpoint 注入的 agent_key → bot_id 映射
messages: 原始消息列表(已由 endpoint 追加到 buffer,留空)
wait_seconds: 等待窗口(默认 6 秒,测试时可缩短) wait_seconds: 等待窗口(默认 6 秒,测试时可缩短)
""" """
# 注入当前调用上下文
self._current_bot_id_mapping = bot_id_mapping
from app.service.session_buffer import SessionBuffer from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
...@@ -129,7 +122,7 @@ class MessageGate: ...@@ -129,7 +122,7 @@ class MessageGate:
decision = await self._classify_and_rewrite( decision = await self._classify_and_rewrite(
session_id=session_id, session_id=session_id,
pending=pending, pending=pending,
agent_codes=list(self._current_bot_id_mapping.keys()), agent_codes=list(bot_id_mapping.keys()),
) )
# 步骤 8:根据 intent 分支 # 步骤 8:根据 intent 分支
...@@ -146,6 +139,7 @@ class MessageGate: ...@@ -146,6 +139,7 @@ class MessageGate:
user_id=user_id, user_id=user_id,
decision=decision, decision=decision,
pending=pending, pending=pending,
bot_id_mapping=bot_id_mapping,
) )
buffer.clear_pending() buffer.clear_pending()
return return
...@@ -157,7 +151,7 @@ class MessageGate: ...@@ -157,7 +151,7 @@ class MessageGate:
user_id=user_id, user_id=user_id,
decision=decision, decision=decision,
pending=pending, pending=pending,
bot_id_mapping=self._current_bot_id_mapping, bot_id_mapping=bot_id_mapping,
) )
buffer.clear_pending() buffer.clear_pending()
...@@ -168,8 +162,6 @@ class MessageGate: ...@@ -168,8 +162,6 @@ class MessageGate:
agent_codes: Optional[List[str]] = None, agent_codes: Optional[List[str]] = None,
) -> "GateDecision": ) -> "GateDecision":
"""调 LLM 进行意图分类 + query 重写。""" """调 LLM 进行意图分类 + query 重写。"""
from app.service.memory import SessionMemory
# 合并文本 # 合并文本
merged_text = "\n".join( merged_text = "\n".join(
m.get("msg_content", "") m.get("msg_content", "")
...@@ -287,6 +279,7 @@ class MessageGate: ...@@ -287,6 +279,7 @@ class MessageGate:
user_id: str, user_id: str,
decision: "GateDecision", decision: "GateDecision",
pending: List[Dict[str, Any]], pending: List[Dict[str, Any]],
bot_id_mapping: Dict[str, str],
) -> None: ) -> None:
"""casual 分支:直接发 IM 回复,并记录 user + assistant 到 history。""" """casual 分支:直接发 IM 回复,并记录 user + assistant 到 history。"""
if not decision.reply: if not decision.reply:
...@@ -306,7 +299,7 @@ class MessageGate: ...@@ -306,7 +299,7 @@ class MessageGate:
"response_content": decision.reply, "response_content": decision.reply,
"room_id": room_id, "room_id": room_id,
"mentioned_list": [user_id], "mentioned_list": [user_id],
"bot_id_mapping": self._current_bot_id_mapping, "bot_id_mapping": bot_id_mapping,
}) })
async def _handle_actionable( async def _handle_actionable(
...@@ -359,6 +352,8 @@ class MessageGate: ...@@ -359,6 +352,8 @@ class MessageGate:
task.add_done_callback(lambda t: self._running_tasks.pop(session_id, None)) task.add_done_callback(lambda t: self._running_tasks.pop(session_id, None))
async def close(self) -> None: async def close(self) -> None:
"""清理资源(Phase 1 简化版)。""" """清理资源:取消运行中的任务并清空状态。"""
for task in list(self._running_tasks.values()):
task.cancel()
self._running_tasks.clear() self._running_tasks.clear()
self._session_locks.clear() self._session_locks.clear()
\ No newline at end of file \ No newline at end of file
...@@ -60,7 +60,6 @@ def message_gate_with_deps(): ...@@ -60,7 +60,6 @@ def message_gate_with_deps():
main_agent_key="main", main_agent_key="main",
model=mock_model, model=mock_model,
) )
gate._current_bot_id_mapping = {"main": "bot-001"}
return gate return gate
...@@ -82,7 +81,6 @@ async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps): ...@@ -82,7 +81,6 @@ async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
intent="actionable", intent="actionable",
rewritten_query="请分析文件 [url]", rewritten_query="请分析文件 [url]",
)) ))
gate._dispatch_to_agent_hub = AsyncMock()
# 追加 file 消息到 buffer # 追加 file 消息到 buffer
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
...@@ -100,7 +98,6 @@ async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps): ...@@ -100,7 +98,6 @@ async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
room_id="r1", room_id="r1",
user_id="u1", user_id="u1",
bot_id_mapping={"main": "bot-001"}, bot_id_mapping={"main": "bot-001"},
messages=[],
) )
# 等待 0.01s 后分类被调用 # 等待 0.01s 后分类被调用
assert gate._classify_and_rewrite.await_count == 1 assert gate._classify_and_rewrite.await_count == 1
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!