From 3d94a476bf794ec9b4fe72f2b7b57831162ec0f6 Mon Sep 17 00:00:00 2001 From: Andy Yang Date: Sun, 3 May 2026 22:31:10 +0800 Subject: [PATCH] fix(memory): dedupe episode write on duplicate streaming Done AgentFinalAnswer may carry Done:true more than once (e.g. finish chunk plus EOF). Guard AddEpisode with sync.Once so memory persists once per turn, consistent with qa.go completion handling. Co-authored-by: Cursor --- .../service/chat_pipeline/memory.go | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/internal/application/service/chat_pipeline/memory.go b/internal/application/service/chat_pipeline/memory.go index c2429d6d..0fdd11b9 100644 --- a/internal/application/service/chat_pipeline/memory.go +++ b/internal/application/service/chat_pipeline/memory.go @@ -3,6 +3,7 @@ package chatpipeline import ( "context" "fmt" + "sync" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/logger" @@ -118,6 +119,7 @@ func (p *MemoryPlugin) handleStorage( // If streaming, subscribe to events if chatManage.EventBus != nil { var fullResponse string + var storeOnce sync.Once userID := chatManage.UserID sessionID := chatManage.SessionID bgCtx := context.WithoutCancel(ctx) @@ -129,15 +131,19 @@ func (p *MemoryPlugin) handleStorage( } fullResponse += data.Content if data.Done { - messages := []types.Message{ - {Role: "user", Content: chatManage.Query}, - {Role: "assistant", Content: fullResponse}, - } - go func() { - if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil { - logger.Errorf(bgCtx, "failed to add episode: %v", err) + // Stream layer may emit Done:true twice (e.g. finish_reason chunk + EOF sentinel). + // qa.go dedupes with completionHandled; keep memory writes consistent with one episode only. + storeOnce.Do(func() { + messages := []types.Message{ + {Role: "user", Content: chatManage.Query}, + {Role: "assistant", Content: fullResponse}, } - }() + go func() { + if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil { + logger.Errorf(bgCtx, "failed to add episode: %v", err) + } + }() + }) } return nil })