From c2043d0f6de977036c0322a72f0995bafac326c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=93=B2=E8=8A=B3?= <34058239+zhangzhefang-github@users.noreply.github.com> Date: Fri, 21 Nov 2025 10:34:55 +0800 Subject: [PATCH] fix: allow API to access conversations created before upgrade to 1.10.0 (#28462) Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> --- api/services/end_user_service.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/api/services/end_user_service.py b/api/services/end_user_service.py index aa4a2e46ec..81098e95bb 100644 --- a/api/services/end_user_service.py +++ b/api/services/end_user_service.py @@ -1,11 +1,15 @@ +import logging from collections.abc import Mapping +from sqlalchemy import case from sqlalchemy.orm import Session from core.app.entities.app_invoke_entities import InvokeFrom from extensions.ext_database import db from models.model import App, DefaultEndUserSessionID, EndUser +logger = logging.getLogger(__name__) + class EndUserService: """ @@ -32,18 +36,36 @@ class EndUserService: user_id = DefaultEndUserSessionID.DEFAULT_SESSION_ID with Session(db.engine, expire_on_commit=False) as session: + # Query with ORDER BY to prioritize exact type matches while maintaining backward compatibility + # This single query approach is more efficient than separate queries end_user = ( session.query(EndUser) .where( EndUser.tenant_id == tenant_id, EndUser.app_id == app_id, EndUser.session_id == user_id, - EndUser.type == type, + ) + .order_by( + # Prioritize records with matching type (0 = match, 1 = no match) + case((EndUser.type == type, 0), else_=1) ) .first() ) - if end_user is None: + if end_user: + # If found a legacy end user with different type, update it for future consistency + if end_user.type != type: + logger.info( + "Upgrading legacy EndUser %s from type=%s to %s for session_id=%s", + end_user.id, + end_user.type, + type, + user_id, + ) + end_user.type = type + session.commit() + else: + # Create new end user if none exists end_user = EndUser( tenant_id=tenant_id, app_id=app_id,