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
+4
View File
@@ -106,6 +106,10 @@ func (e *AgentEngine) streamLLMToEventBus(
// accumulated call in the final chunk. Decode once more after assembly so
// aliases split across provider chunks cannot leak into tool execution.
e.resourceRefs.DecodeToolCalls(result.ToolCalls)
if orphans := e.resourceRefs.OrphanAliases(result.Content); len(orphans) > 0 {
logger.Warnf(ctx, "[Agent][Stream] Model emitted %d unresolvable resource alias(es): %v",
len(orphans), orphans)
}
// Stream diagnostic summary: helps identify non-streaming patterns
streamDuration := time.Duration(0)
@@ -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)
}
+34
View File
@@ -23,6 +23,11 @@ var storedRefRE = regexp.MustCompile(
`(?:local|minio|cos|tos|s3|oss|ks3|obs)://[^\s)\]>"']+`,
)
// aliasShapeRE matches the alias syntax produced by EncodeText. It is used only
// to spot alias-shaped tokens the model emitted that the registry cannot map
// back — either a hallucinated reference or a coincidental collision.
var aliasShapeRE = regexp.MustCompile(`res:\d{4,}`)
// Registry assigns low-entropy, request-local aliases to stable resource
// handles. It is safe to reuse across all rounds of one Agent execution.
type Registry struct {
@@ -120,6 +125,35 @@ func (r *Registry) DecodeToolCalls(toolCalls []types.LLMToolCall) {
}
}
// OrphanAliases returns the distinct alias-shaped tokens in an already-decoded
// string that the registry cannot resolve. A non-empty result means the model
// emitted a reference no real resource backs (hallucination) or the user text
// happened to collide with the alias syntax. Callers should log/observe these
// rather than surfacing them to end users as broken links.
func (r *Registry) OrphanAliases(decoded string) []string {
if decoded == "" {
return nil
}
var orphans []string
seen := make(map[string]struct{})
for _, match := range aliasShapeRE.FindAllString(decoded, -1) {
if r != nil {
r.mu.RLock()
_, known := r.aliasToRef[match]
r.mu.RUnlock()
if known {
continue
}
}
if _, dup := seen[match]; dup {
continue
}
seen[match] = struct{}{}
orphans = append(orphans, match)
}
return orphans
}
func (r *Registry) aliases() []string {
r.mu.RLock()
defer r.mu.RUnlock()
+17
View File
@@ -41,3 +41,20 @@ func TestStreamDecoderRestoresSplitAlias(t *testing.T) {
require.Equal(t, ref+" afte", d.Feed("001 after"))
require.Equal(t, "r", d.Flush())
}
func TestOrphanAliasesReportsUnresolvableTokens(t *testing.T) {
r := NewRegistry()
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
require.Equal(t, "res:0001", r.EncodeText(ref))
// Known alias resolves and leaves no orphan once decoded.
require.Nil(t, r.OrphanAliases(r.DecodeText("see res:0001")))
// A reference the registry never assigned is reported (deduplicated).
require.Equal(t, []string{"res:0099"}, r.OrphanAliases("look at res:0099 and res:0099"))
}
func TestOrphanAliasesNilRegistry(t *testing.T) {
var r *Registry
require.Equal(t, []string{"res:0001"}, r.OrphanAliases("res:0001"))
}