RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(sdk-sessions): restore session API contracts (#21746)
Sbaaoui Idriss34a53be39cc8
diff --git a/internal/dao/chat_session.go b/internal/dao/chat_session.goindex 210b299771..069ab32720 100644--- a/internal/dao/chat_session.go+++ b/internal/dao/chat_session.go@@ -154,7 +154,7 @@ func (dao *ChatSessionDAO) DeleteByID(ctx context.Context, db *gorm.DB, id strin}// ListByResourceIDs lists sessions for a chat, optionally restricted to sessionIDs.-func (dao *ChatSessionDAO) ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, terms []OrderTerm, page, pageSize int, options ...ConversationHistoryOptions) ([]*entity.ChatSession, int64, error) {+func (dao *ChatSessionDAO) ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name, sessionUserID string, terms []OrderTerm, page, pageSize int, options ...ConversationHistoryOptions) ([]*entity.ChatSession, int64, error) {if sessionIDs != nil && len(sessionIDs) == 0 {return []*entity.ChatSession{}, 0, nil}@@ -169,6 +169,9 @@ func (dao *ChatSessionDAO) ListByResourceIDs(ctx context.Context, db *gorm.DB, cif name != "" {query = query.Where("name = ?", name)}+ if sessionUserID != "" {+ query = query.Where("user_id = ?", sessionUserID)+ }var total int64if err := query.Count(&total).Error; err != nil {return nil, 0, errdiff --git a/internal/handler/chat_session.go b/internal/handler/chat_session.goindex 66a49150e9..50403ee32d 100644--- a/internal/handler/chat_session.go+++ b/internal/handler/chat_session.go@@ -133,7 +133,7 @@ func (h *ChatSessionHandler) ListChatSessions(c *gin.Context) {return}options.NoHistory = includeHistory == "false" || includeHistory == "False"- result, err := h.chatSessionService.ListChatSessions(ctx, userID, chatID, c.Query("id"), c.Query("name"), terms, page, pageSize, options)+ result, err := h.chatSessionService.ListChatSessions(ctx, userID, chatID, c.Query("id"), c.Query("name"), c.Query("user_id"), terms, page, pageSize, options)if err != nil {if respondPermissionErrorIf(c, err, true) {returndiff --git a/internal/handler/chat_session_sdk_test.go b/internal/handler/chat_session_sdk_test.gonew file mode 100644index 0000000000..c806c4a627--- /dev/null+++ b/internal/handler/chat_session_sdk_test.go@@ -0,0 +1,84 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package handler++import (+ "encoding/json"+ "net/http"+ "testing"++ "github.com/gin-gonic/gin"+ "ragflow/internal/dao"+ "ragflow/internal/entity"+ "ragflow/internal/service"+)++func TestListChatSessionsPublicSchemaAndUserFilter(t *testing.T) {+ for _, tc := range []struct {+ query string+ count, total int+ }{+ {"", 3, 3}, {"user_id=user-1&page_size=1", 1, 2}, {"user_id=absent", 0, 0}, {"user_id=user-1&id=session-a", 1, 1}, {"user_id=absent&id=session-a", 0, 0},+ } {+ t.Run(tc.query, func(t *testing.T) {+ c, w, db := setupGinContextWithUserAndDB(t, http.MethodGet, "/?"+tc.query)+ if err := db.AutoMigrate(&entity.Chat{}, &entity.ChatSession{}, &entity.ConversationMessage{}); err != nil {+ t.Fatal(err)+ }+ if err := db.Create(&entity.Chat{ID: "chat", TenantID: "user-1", LLMSetting: entity.JSONMap{}, PromptConfig: entity.JSONMap{}, KBIDs: entity.JSONSlice{}, Status: sptr("1")}).Error; err != nil {+ t.Fatal(err)+ }+ for _, id := range []string{"session-a", "session-b"} {+ if err := dao.NewChatSessionDAO().Create(t.Context(), db, &entity.ChatSession{ID: id, DialogID: "chat", UserID: sptr("user-1"), Message: json.RawMessage(`[{"role":"assistant","content":"hello"}]`)}); err != nil {+ t.Fatal(err)+ }+ }++ if err := dao.NewChatSessionDAO().Create(t.Context(), db, &entity.ChatSession{ID: "session-other-user", DialogID: "chat", UserID: sptr("external-user"), Message: json.RawMessage(`[{"role":"assistant","content":"hello"}]`)}); err != nil {+ t.Fatal(err)+ }+ c.Params = gin.Params{{Key: "chat_id", Value: "chat"}}+ NewChatSessionHandler(service.NewChatSessionService(), nil).ListChatSessions(c)+ var response struct {+ Code int `json:"code"`+ Data []map[string]interface{} `json:"data"`+ Total int `json:"total"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if response.Code != 0 || len(response.Data) != tc.count || response.Total != tc.total {+ t.Fatalf("response=%s", w.Body.String())+ }+ for _, row := range response.Data {+ if row["chat_id"] != "chat" {+ t.Fatal(row)+ }+ messages, ok := row["messages"].([]interface{})+ if !ok || len(messages) != 1 {+ t.Fatal(row)+ }+ if _, ok := row["dialog_id"]; ok {+ t.Fatal(row)+ }+ if _, ok := row["message"]; ok {+ t.Fatal(row)+ }+ }+ })+ }+}diff --git a/internal/handler/session_history_test.go b/internal/handler/session_history_test.goindex 061c447eca..63661df58b 100644--- a/internal/handler/session_history_test.go+++ b/internal/handler/session_history_test.go@@ -146,7 +146,7 @@ func TestSessionHistoryQueryFlags(t *testing.T) {t.Fatal(err)}key := "messages"- if endpoint != "chat" {+ if endpoint != "chat" && endpoint != "chat_list" {key = "message"}var messages []map[string]interface{}diff --git a/internal/service/chat_session.go b/internal/service/chat_session.goindex 31db912ad4..494e11fe71 100644--- a/internal/service/chat_session.go+++ b/internal/service/chat_session.go@@ -49,7 +49,7 @@ type chatSessionStore interface {Create(ctx context.Context, db *gorm.DB, conv *entity.ChatSession) errorUpdateByID(ctx context.Context, db *gorm.DB, id string, updates map[string]interface{}) errorDeleteByID(ctx context.Context, db *gorm.DB, id string) error- ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, options ...dao.ConversationHistoryOptions) ([]*entity.ChatSession, int64, error)+ ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name, sessionUserID string, terms []dao.OrderTerm, page, pageSize int, options ...dao.ConversationHistoryOptions) ([]*entity.ChatSession, int64, error)GetDialogByID(ctx context.Context, db *gorm.DB, chatID string) (*entity.Chat, error)}@@ -112,7 +112,7 @@ type ListChatSessionsRequest struct {// ListChatSessionsResponse list chat sessions responsetype ListChatSessionsResponse struct {- Sessions []*entity.ChatSession+ Sessions []*ChatSessionPayloadTotal int64}@@ -130,19 +130,19 @@ type ChatSessionPayload struct {}// ListChatSessions lists chat sessions for a dialog-func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatID, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, options ...dao.ConversationHistoryOptions) (*ListChatSessionsResponse, error) {+func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatID, sessionID, name, sessionUserID string, terms []dao.OrderTerm, page, pageSize int, options ...dao.ConversationHistoryOptions) (*ListChatSessionsResponse, error) {if err := checkChatPermission(ctx, s.permissionChecker, userID, chatID, permission.OperationRead); err != nil {_, normalizedErr := normalizeChatPermissionError(err)return nil, normalizedErr}// List chat sessions- sessions, total, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, nil, sessionID, name, terms, page, pageSize, sessionHistoryOptions(options...))+ sessions, total, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, nil, sessionID, name, sessionUserID, terms, page, pageSize, sessionHistoryOptions(options...))if err != nil {return nil, err}if len(sessions) == 0 {- return &ListChatSessionsResponse{Sessions: sessions, Total: total}, nil+ return &ListChatSessionsResponse{Sessions: []*ChatSessionPayload{}, Total: total}, nil}checker := s.permissionChecker@@ -162,10 +162,10 @@ func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatIfor _, ref := range accessible {allowedIDs[ref.ID] = true}- filtered := make([]*entity.ChatSession, 0, len(accessible))+ filtered := make([]*ChatSessionPayload, 0, len(accessible))for _, session := range sessions {if allowedIDs[session.ID] {- filtered = append(filtered, session)+ filtered = append(filtered, s.buildSessionPayload(session, nil, false, options...))}}@@ -287,7 +287,7 @@ func (s *ChatSessionService) DeleteSessions(ctx context.Context, userID, chatIDif len(sessionIDs) == 0 {return map[string]interface{}{}, "success", common.CodeSuccess, nil}- sessions, _, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, sessionIDs, "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 0, -1, dao.ConversationHistoryOptions{NoHistory: true})+ sessions, _, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, sessionIDs, "", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 0, -1, dao.ConversationHistoryOptions{NoHistory: true})if err != nil {return nil, "", common.CodeServerError, err}diff --git a/internal/service/chat_session_contract_test.go b/internal/service/chat_session_contract_test.goindex 1b293cb018..be55d65bd1 100644--- a/internal/service/chat_session_contract_test.go+++ b/internal/service/chat_session_contract_test.go@@ -150,7 +150,7 @@ func TestListChatSessionsChecksChatPermissionWhenThereAreNoSessions(t *testing.TpermissionChecker: emptyChatSessionScopeChecker{checkErr: permission.ErrPermissionDenied},}- result, err := svc.ListChatSessions(t.Context(), "outsider", "chat-1", "", "", nil, 1, 20)+ result, err := svc.ListChatSessions(t.Context(), "outsider", "chat-1", "", "", "", nil, 1, 20)if result != nil {t.Fatalf("expected no response for unauthorized chat, got %+v", result)}diff --git a/internal/service/chat_session_test.go b/internal/service/chat_session_test.goindex b46649eceb..befecef110 100644--- a/internal/service/chat_session_test.go+++ b/internal/service/chat_session_test.go@@ -154,7 +154,7 @@ func (f *fakeSessionStore) DeleteByID(ctx context.Context, db *gorm.DB, id strinreturn nil}-func (f *fakeSessionStore) ListByResourceIDs(_ context.Context, _ *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, _ []dao.OrderTerm, _, pageSize int, _ ...dao.ConversationHistoryOptions) ([]*entity.ChatSession, int64, error) {+func (f *fakeSessionStore) ListByResourceIDs(_ context.Context, _ *gorm.DB, chatID string, sessionIDs []string, sessionID, name, sessionUserID string, _ []dao.OrderTerm, _, pageSize int, _ ...dao.ConversationHistoryOptions) ([]*entity.ChatSession, int64, error) {allowedIDs := make(map[string]struct{}, len(sessionIDs))for _, id := range sessionIDs {allowedIDs[id] = struct{}{}@@ -170,6 +170,9 @@ func (f *fakeSessionStore) ListByResourceIDs(_ context.Context, _ *gorm.DB, chatif sessionID != "" && s.ID != sessionID {continue}+ if sessionUserID != "" && (s.UserID == nil || *s.UserID != sessionUserID) {+ continue+ }if name != "" {var sessionName stringif s.Name != nil {@@ -585,7 +588,7 @@ func TestListChatSessions_Success(t *testing.T) {ctx := t.Context()terms := []dao.OrderTerm{{Column: "create_time", Desc: true}}- resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})+ resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})if err != nil {t.Fatalf("unexpected error: %v", err)}@@ -598,7 +601,7 @@ func TestListChatSessions_Success(t *testing.T) {}}for page, wantCount := range map[int]int{4: 10, 5: 1, 6: 0} {- resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", terms, page, 10, dao.ConversationHistoryOptions{NoHistory: true})+ resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", terms, page, 10, dao.ConversationHistoryOptions{NoHistory: true})if err != nil {t.Fatalf("page %d: %v", page, err)}@@ -606,11 +609,11 @@ func TestListChatSessions_Success(t *testing.T) {t.Fatalf("page %d: got total=%d and %d sessions, want total=41 and %d sessions", page, resp.Total, len(resp.Sessions), wantCount)}}- resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", terms, 1, 0, dao.ConversationHistoryOptions{NoHistory: true})+ resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", terms, 1, 0, dao.ConversationHistoryOptions{NoHistory: true})if err != nil || resp.Total != 41 || len(resp.Sessions) != 0 {t.Fatalf("zero page size: got response=%+v err=%v, want total=41 and no sessions", resp, err)}- resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "session-01", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})+ resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "session-01", "", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})if err != nil || resp.Total != 1 || len(resp.Sessions) != 1 {t.Fatalf("ID filter: got response=%+v err=%v, want total=1 and one session", resp, err)}@@ -626,7 +629,7 @@ func TestListChatSessions_NotOwner(t *testing.T) {}ctx := t.Context()- _, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 1, 30)+ _, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 1, 30)if err == nil || err.Error() != "Resource not found" {t.Fatalf("got %v", err)}diff --git a/sdk/python/ragflow_sdk/modules/chat.py b/sdk/python/ragflow_sdk/modules/chat.pyindex 18822eb4ff..4ddbaa4cdd 100644--- a/sdk/python/ragflow_sdk/modules/chat.py+++ b/sdk/python/ragflow_sdk/modules/chat.py@@ -1,5 +1,5 @@#-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.@@ -50,7 +50,9 @@ class Chat(Base):return Session(self.rag, res["data"])raise Exception(res.get("message"))- def list_sessions(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True, id: str = None, name: str = None, user_id: str = None) -> list[Session]:+ def list_sessions(+ self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True, id: str | None = None, name: str | None = None, user_id: str | None = None+ ) -> list[Session]:res = self.get(f"/chats/{self.id}/sessions", {"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "name": name, "user_id": user_id})res = res.json()if res.get("code") == 0:diff --git a/sdk/python/ragflow_sdk/modules/session.py b/sdk/python/ragflow_sdk/modules/session.pyindex c36f4f6631..ad005e0c05 100644--- a/sdk/python/ragflow_sdk/modules/session.py+++ b/sdk/python/ragflow_sdk/modules/session.py@@ -1,5 +1,5 @@#-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.@@ -120,6 +120,9 @@ class Session(Base):except json.JSONDecodeError:continue # Skip lines that are not valid JSON+ if json_data.get("code", 0) != 0:+ raise Exception(json_data.get("message", "Unknown API error"))+event = json_data.get("event", None)if event:if self.__session_type == "agent" and event not in {"message", "message_end"}:@@ -144,6 +147,8 @@ class Session(Base):json_data = res.json()except ValueError:raise Exception(f"Invalid response {res}")+ if json_data.get("code", 0) != 0:+ raise Exception(json_data.get("message", "Unknown API error"))yield self._structure_answer(json_data["data"])def _structure_answer(self, json_data):diff --git a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.pyindex fad0b581c0..9393a5aaad 100644--- a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py+++ b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py@@ -281,20 +281,28 @@ def test_session_stream_stops_before_trailing_messages(monkeypatch, session_type@pytest.mark.p2-def test_chat_stream_preserves_runtime_error_answer(monkeypatch):+def test_chat_stream_raises_api_error_with_answer(monkeypatch):session = Session(None, {"id": "session", "chat_id": "parent"})response = _DummyStreamResponse(['data:{"code":500,"message":"Session not found!","data":{"answer":"**ERROR**: Session not found!","reference":[]}}'])monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response)+ with pytest.raises(Exception, match="^Session not found!$"):+ list(session.ask("question", stream=True))+++def test_chat_stream_preserves_runtime_error_answer(monkeypatch):+ session = Session(None, {"id": "session", "chat_id": "parent"})+ response = _DummyStreamResponse(['data:{"code":0,"message":"success","data":{"answer":"**ERROR**: runtime failure","reference":[]}}'])+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response)messages = list(session.ask("question", stream=True))assert len(messages) == 1- assert messages[0].content == "**ERROR**: Session not found!"+ assert messages[0].content == "**ERROR**: runtime failure"assert messages[0].reference is None@pytest.mark.p2@pytest.mark.parametrize("session_type", ["chat", "agent"])@pytest.mark.parametrize("stream", [False, True])[email protected](reason="Python SDK Session.ask ignores nonzero response codes: Go validation errors lose their message in KeyError('data') instead of raising the API error")def test_session_ask_preserves_api_error_message(monkeypatch, session_type, stream):session = Session(None, {"id": "session", f"{session_type}_id": "parent"})error = {"code": 102, "message": "Session not found!"}diff --git a/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.pyindex f2660c9688..e5e825c873 100644--- a/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py+++ b/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py@@ -105,16 +105,12 @@ class TestSessionsWithChatAssistantList:with pytest.raises(Exception, match="^Resource not found$"):chat.list_sessions()- @pytest.mark.skip(reason="Go ListChatSessions never reads user_id or filters by it (internal/handler/chat_session.go); remove when documented user_id filtering is implemented")@pytest.mark.parametrize("combined", [False, True])def test_user_id(self, add_sessions_with_chat_assistant, combined):chat, sessions = add_sessions_with_chat_assistantfilters = {"id": sessions[0].id, "name": sessions[0].name} if combined else {}assert chat.list_sessions(user_id="nonexistent-session-user", **filters) == []- @pytest.mark.skip(- reason="Go list serializes entity.ChatSession as dialog_id/message, but SDK Session requires chat_id/messages (internal/handler/chat_session.go and sdk/python/ragflow_sdk/modules/session.py); remove when list returns SDK session schema"- )def test_list_response_session_contract(self, chat):created = chat.create_session()listed = chat.list_sessions(id=created.id)@@ -237,6 +233,32 @@ def test_sdk_crud_http_contract(monkeypatch, operation):assert kwargs["headers"] == {"Authorization": "Bearer unit-token"}[email protected]("field", ["id", "name", "user_id"])+def test_list_sessions_optional_filter_types(monkeypatch, field):+ from beartype.roar import BeartypeCallHintParamViolation+ from ragflow_sdk import Chat++ chat = Chat(None, {"id": "chat-1"})++ class Response:+ def json(self):+ return {"code": 0, "data": []}++ calls = []++ def get(path, params):+ calls.append((path, params))+ return Response()++ monkeypatch.setattr(chat, "get", get)+ assert chat.list_sessions() == []+ assert chat.list_sessions(**{field: None}) == []+ assert calls[0] == calls[1]+ with pytest.raises(BeartypeCallHintParamViolation):+ chat.list_sessions(**{field: 1})+ assert len(calls) == 2++@pytest.mark.parametrize("operation", ["create", "update", "delete"])def test_sdk_crud_api_errors(monkeypatch, operation):from ragflow_sdk import Chat