Commit d7cc3627 by sunqi02 Committed by 胡悦

fix: save_to_db uses short-lived SQLAlchemy session to prevent Broken pipe

Also writes intent_session field to DB. The with db_factory() as db pattern
ensures pool_pre_ping fires on every write, preventing stale connections.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent f8f6f30f
......@@ -100,9 +100,8 @@ class ActiveSessionService:
)
def save_to_db(self, session_id: str) -> None:
"""将内存中的 session 持久化到 DB。"""
if not self._db:
logger.warning("[save_to_db] session=%s _db 为 None,跳过持久化", session_id)
if not self._db_factory:
logger.warning("[save_to_db] session=%s db_factory 为 None,跳过持久化", session_id)
return
data = self.store.get(session_id)
......@@ -111,34 +110,42 @@ class ActiveSessionService:
return
history = data.get("conversation_history") or []
intent_session = data.get("intent_session", "")
intent_session_str = (
intent_session
if isinstance(intent_session, str)
else json.dumps(intent_session, ensure_ascii=False)
)
logger.info(
"[save_to_db] session=%s 即将写入 DB,conversation_history 长度=%d",
session_id, len(history),
"[save_to_db] session=%s intent_session 长度=%d, conversation_history 长度=%d",
session_id, len(intent_session_str), len(history),
)
try:
existing = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
with self._db_factory() as db:
existing = db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
self._db.add(db_sess)
self._db.commit()
)
existing.intent_session = intent_session_str
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
intent_session=intent_session_str,
)
db.add(db_sess)
db.commit()
except Exception:
self._db.rollback()
logger.exception("Failed to persist session %s to DB", session_id)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!