feat(chat): implement orphan alias detection and logging in chat completion and streaming

Add functionality to detect unresolvable resource aliases emitted by the model during chat completion and streaming. Introduce logging for these orphan aliases to aid in debugging and improve the handling of resource references. Update the stream processing to ensure held aliases are flushed upon cancellation, preventing data loss. Include tests to verify the correct reporting of orphan aliases.
This commit is contained in:
wizardchen
2026-07-15 16:49:43 +08:00
committed by lyingbug
parent 6d14cc3536
commit 38c594aec3
6 changed files with 210 additions and 16 deletions
@@ -68,6 +68,12 @@ func (p *PluginChatCompletion) OnEvent(
return ErrModelCall.WithError(err)
}
resourceRefs.DecodeResponse(chatResponse)
if orphans := resourceRefs.OrphanAliases(chatResponse.Content); len(orphans) > 0 {
pipelineWarn(ctx, "Completion", "orphan_resource_aliases", map[string]interface{}{
"session_id": chatManage.SessionID,
"aliases": orphans,
})
}
pipelineInfo(ctx, "Completion", "output", map[string]interface{}{
"answer_preview": chatResponse.Content,
@@ -129,9 +129,34 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
thinkingOpen = false
}
// flushDecoders drains any alias suffix the stream decoders held back to
// bridge references split across provider chunks. Both the normal close
// and the cancellation path must call this, otherwise a resource
// reference in flight at teardown is silently dropped (and never
// persisted, since the assistant message is saved from these events).
flushDecoders := func() {
if tail := thinkingDecoder.Flush(); tail != "" {
_ = eventBus.Emit(ctx, types.Event{
ID: thinkingID,
Type: types.EventType(event.EventAgentThought),
SessionID: chatManage.SessionID,
Data: event.AgentThoughtData{Content: tail},
})
}
if tail := answerDecoder.Flush(); tail != "" {
_ = eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{Content: tail},
})
}
}
for {
select {
case <-ctx.Done():
flushDecoders()
closeThinking()
pipelineInfo(ctx, "Stream", "context_cancelled", map[string]interface{}{
"session_id": chatManage.SessionID,
@@ -140,22 +165,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
case response, ok := <-responseChan:
if !ok {
if tail := thinkingDecoder.Flush(); tail != "" {
_ = eventBus.Emit(ctx, types.Event{
ID: thinkingID,
Type: types.EventType(event.EventAgentThought),
SessionID: chatManage.SessionID,
Data: event.AgentThoughtData{Content: tail},
})
}
if tail := answerDecoder.Flush(); tail != "" {
_ = eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{Content: tail},
})
}
flushDecoders()
closeThinking()
pipelineInfo(ctx, "Stream", "channel_close", map[string]interface{}{
"session_id": chatManage.SessionID,
@@ -0,0 +1,123 @@
package chatpipeline
import (
"context"
"sync"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
// syncEventBus is a thread-safe recorder; the stream plugin emits from a
// background goroutine so the test must guard concurrent appends.
type syncEventBus struct {
mu sync.Mutex
events []types.Event
}
func (b *syncEventBus) On(types.EventType, types.EventHandler) {}
func (b *syncEventBus) Emit(_ context.Context, evt types.Event) error {
b.mu.Lock()
defer b.mu.Unlock()
b.events = append(b.events, evt)
return nil
}
func (b *syncEventBus) finalAnswerContents() []string {
b.mu.Lock()
defer b.mu.Unlock()
var out []string
for _, evt := range b.events {
if evt.Type != types.EventType(event.EventAgentFinalAnswer) {
continue
}
if data, ok := evt.Data.(event.AgentFinalAnswerData); ok {
out = append(out, data.Content)
}
}
return out
}
// openStreamChat returns a buffered channel preloaded with chunks and never
// closes it, so the stream plugin blocks on the channel until ctx is cancelled
// — deterministically exercising the ctx.Done() branch.
type openStreamChat struct {
chunks []types.StreamResponse
}
func (m *openStreamChat) Chat(context.Context, []chat.Message, *chat.ChatOptions) (*types.ChatResponse, error) {
return nil, nil
}
func (m *openStreamChat) ChatStream(
context.Context, []chat.Message, *chat.ChatOptions,
) (<-chan types.StreamResponse, error) {
ch := make(chan types.StreamResponse, len(m.chunks))
for _, c := range m.chunks {
ch <- c
}
return ch, nil // intentionally left open
}
func (m *openStreamChat) GetModelName() string { return "mock" }
func (m *openStreamChat) GetModelID() string { return "mock" }
// stubModelService only needs GetChatModel; the rest is unused for this test.
type stubModelService struct {
interfaces.ModelService
model chat.Chat
}
func (s *stubModelService) GetChatModel(context.Context, string) (chat.Chat, error) {
return s.model, nil
}
// TestStreamFlushesHeldAliasOnCancel verifies that when the request is cancelled
// mid-stream, the decoder's held-back alias suffix is flushed (emitted) rather
// than silently dropped. Without the ctx.Done() flush, "res:0" would be lost.
func TestStreamFlushesHeldAliasOnCancel(t *testing.T) {
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
bus := &syncEventBus{}
model := &openStreamChat{chunks: []types.StreamResponse{
// Ends with a partial alias prefix ("res:0"), so the stream decoder
// holds it back waiting for the rest that never arrives before cancel.
{ResponseType: types.ResponseTypeAnswer, Content: "hello res:0"},
}}
chatManage := &types.ChatManage{}
chatManage.SessionID = "sess-cancel"
chatManage.UserContent = ref // seeds the registry so res:0001 becomes a known alias
chatManage.EventBus = bus
ctx, cancel := context.WithCancel(context.Background())
plugin := &PluginChatCompletionStream{modelService: &stubModelService{model: model}}
require.Nil(t, plugin.OnEvent(ctx, types.CHAT_COMPLETION_STREAM, chatManage, func() *PluginError { return nil }))
// Wait until the pre-hold content has been emitted, then cancel.
require.Eventually(t, func() bool {
for _, c := range bus.finalAnswerContents() {
if c == "hello " {
return true
}
}
return false
}, 2*time.Second, 5*time.Millisecond)
cancel()
// After cancel, the held "res:0" suffix must be flushed as a final-answer chunk.
require.Eventually(t, func() bool {
for _, c := range bus.finalAnswerContents() {
if c == "res:0" {
return true
}
}
return false
}, 2*time.Second, 5*time.Millisecond)
}