Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(agent): recover final-answer context overflow and propagate synthesis errors (#4629)
Raphael Malikianf319acf78358
diff --git a/internal/agent/context_debug.go b/internal/agent/context_debug.goindex 62d8c56e9..300dbd121 100644--- a/internal/agent/context_debug.go+++ b/internal/agent/context_debug.go@@ -58,8 +58,7 @@ func (e *AgentEngine) breakdownContext(messages []chat.Message, tools []chat.Too// Reasoning is the text plus the opaque artifacts replayed with it, so// the line stays comparable to the message total the estimator reports.- if reasoning := est.EstimateString(msg.ReasoningContent) +- est.EstimateReasoningArtifacts(msg); reasoning > 0 {+ if reasoning := est.EstimateReasoning(msg); reasoning > 0 {b.Reasoning += reasoning}for _, tc := range msg.ToolCalls {diff --git a/internal/agent/engine.go b/internal/agent/engine.goindex 7fc477025..a5e3e69aa 100644--- a/internal/agent/engine.go+++ b/internal/agent/engine.go@@ -816,7 +816,9 @@ loop:if e.collaboration != nil && e.collaboration.Child == nil && e.collaborationOwnsFailure(ctx) {return state, fmt.Errorf("parent iteration budget exhausted; remaining delegated work was cancelled")}- e.handleMaxIterations(ctx, query, state, sessionID, messages)+ if err := e.handleMaxIterations(ctx, query, state, sessionID, messages); err != nil {+ return state, err+ }}return state, nildiff --git a/internal/agent/finalize.go b/internal/agent/finalize.goindex feb963308..39165e083 100644--- a/internal/agent/finalize.go+++ b/internal/agent/finalize.go@@ -2,8 +2,10 @@ package agentimport ("context"+ "fmt""time"+ "github.com/Tencent/WeKnora/internal/agent/compaction"agenttools "github.com/Tencent/WeKnora/internal/agent/tools""github.com/Tencent/WeKnora/internal/common""github.com/Tencent/WeKnora/internal/event"@@ -20,6 +22,9 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(sessionID string,conversation []chat.Message,) error {+ if err := ctx.Err(); err != nil {+ return err+ }totalToolCalls := countTotalToolCalls(state.RoundSteps)logger.Infof(ctx, "[Agent][FinalAnswer] Synthesizing from %d steps, %d tool calls",len(state.RoundSteps), totalToolCalls)@@ -41,64 +46,122 @@ func (e *AgentEngine) streamFinalAnswerToEventBus("remaining work and explain any missing evidence. Use the user's requested " +"language and format. Do not claim that an unperformed action " +"succeeded.\"}</runtime_event>"+ if e.finalAnswerNeedsCompaction(messages, runtimeNotice) {+ messages, _ = e.compactFinalAnswerContext(ctx, messages, state.CurrentRound+1,+ runtimeNotice, compaction.ReasonThreshold)+ }// Generate a single ID for this entire final answer streamanswerID := generateEventID("answer")logger.Debugf(ctx, "[Agent][FinalAnswer] AnswerID: %s", answerID)- answerDoneEmitted := false+ answerStreamed := false+ providerDone := false+ terminalContent := ""splitter := agenttools.NewThinkStreamSplitter()- budget := e.clampCompletionBudgetToContext(- e.tokenEstimator.EstimateMessages(- append(append([]chat.Message(nil), messages...), chat.Message{Role: "system", Content: runtimeNotice}),- ),- )- llmResult, err := e.streamLLMToEventBus(- ctx,- messages,- &chat.ChatOptions{- RuntimeNotice: runtimeNotice,- Temperature: e.config.Temperature,- MaxCompletionTokens: budget,- PromptCacheKey: sessionID,- ToolChoice: "none",- }, // Thinking disabled for final answer synthesis- func(chunk *types.StreamResponse, fullContent string) {- // Defensive filter: only emit answer content, skip thinking chunks- if chunk.ResponseType == types.ResponseTypeThinking {- return- }- _, answerContent := splitter.Feed(chunk.Content)- if splitter.TakeAnswerReset() {- _ = e.eventBus.Emit(- ctx,- event.Event{- ID: answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,- Data: event.AgentFinalAnswerData{Replace: true},- },- )- }- if chunk.Done {- _, tail := splitter.Flush()- answerContent += tail- }- if answerContent != "" {- logger.Debugf(ctx, "[Agent][FinalAnswer] Emitting answer chunk: %d chars", len(answerContent))- e.eventBus.Emit(ctx, event.Event{- ID: answerID,- Type: event.EventAgentFinalAnswer,- SessionID: sessionID,- Data: event.AgentFinalAnswerData{- Content: answerContent,- Done: chunk.Done,- },- })+ var llmResult *streamLLMResult+ var err error+ // This phase has its own single overflow retry. The last tool results and+ // the tool-free synthesis request differ from the preceding ReAct round.+ for attempt := 0; attempt < 2; attempt++ {+ if err := ctx.Err(); err != nil {+ return err+ }+ inputTokens := e.finalAnswerInputTokens(messages, runtimeNotice)+ budget := e.clampCompletionBudgetToContext(inputTokens)+ if e.config.MaxContextTokens > 0 && inputTokens+budget > e.config.MaxContextTokens {+ return fmt.Errorf("final answer synthesis cannot fit after compaction: estimated input %d tokens "++ "plus completion budget %d exceeds context window %d", inputTokens, budget, e.config.MaxContextTokens)+ }+ llmResult, err = e.streamLLMToEventBus(+ ctx,+ messages,+ &chat.ChatOptions{+ RuntimeNotice: runtimeNotice,+ Temperature: e.config.Temperature,+ MaxCompletionTokens: budget,+ PromptCacheKey: sessionID,+ ToolChoice: "none",+ }, // Thinking disabled for final answer synthesis+ func(chunk *types.StreamResponse, _ string) {+ // Defensive filter: only emit answer content, skip thinking chunks+ if chunk.ResponseType == types.ResponseTypeThinking {+ return+ }+ _, answerContent := splitter.Feed(chunk.Content)+ if splitter.TakeAnswerReset() {+ _ = e.eventBus.Emit(+ ctx,+ event.Event{+ ID: answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,+ Data: event.AgentFinalAnswerData{Replace: true},+ },+ )+ }if chunk.Done {- answerDoneEmitted = true+ _, tail := splitter.Flush()+ answerContent += tail+ providerDone = true+ }+ // Do not close the answer until the whole stream has succeeded: a+ // later error may require replacing this attempt with a retry.+ if providerDone {+ terminalContent += answerContent+ return}+ if answerContent != "" {+ logger.Debugf(ctx, "[Agent][FinalAnswer] Emitting answer chunk: %d chars", len(answerContent))+ _ = e.eventBus.Emit(ctx, event.Event{+ ID: answerID,+ Type: event.EventAgentFinalAnswer,+ SessionID: sessionID,+ Data: event.AgentFinalAnswerData{+ Content: answerContent,+ },+ })+ answerStreamed = true+ }+ },+ )+ // A provider can report a full window as a length stop instead of an+ // HTTP/stream error. Reuse the ReAct detector, and account for every+ // measured attempt even when its answer is replaced by recovery.+ overflow := compaction.IsOverflowError(err)+ if llmResult != nil && llmResult.Usage != nil {+ state.TurnUsage.Accumulate(*llmResult.Usage)+ if err == nil && e.responseHitContextLimit(&types.ChatResponse{+ FinishReason: llmResult.FinishReason, Usage: *llmResult.Usage,+ }) {+ overflow = true+ err = fmt.Errorf("final answer synthesis reached the context window: finish=%s prompt=%d completion=%d",+ llmResult.FinishReason, llmResult.Usage.PromptTokens, llmResult.Usage.CompletionTokens)}- },- )+ }+ if ctxErr := ctx.Err(); ctxErr != nil {+ return ctxErr+ }+ if err == nil || attempt == 1 || !overflow {+ break+ }+ logger.Warnf(ctx, "[Agent][FinalAnswer] Context overflow; compacting before one retry: %v", err)+ compacted, changed := e.compactFinalAnswerContext(ctx, messages, state.CurrentRound+1,+ runtimeNotice, compaction.ReasonOverflow)+ if ctxErr := ctx.Err(); ctxErr != nil {+ return ctxErr+ }+ if !changed {+ break // Sending the same rejected context again cannot recover.+ }+ messages = compacted+ if answerStreamed {+ _ = e.eventBus.Emit(ctx, event.Event{+ ID: answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,+ Data: event.AgentFinalAnswerData{Replace: true},+ })+ }+ answerStreamed, providerDone, terminalContent = false, false, ""+ splitter = agenttools.NewThinkStreamSplitter()+ }if err != nil {logger.Errorf(ctx, "[Agent][FinalAnswer] Final answer generation failed: %v", err)common.PipelineError(ctx, "Agent", "final_answer_stream_failed", map[string]interface{}{@@ -107,30 +170,11 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(})return err}- if _, tail := splitter.Flush(); tail != "" {- _ = e.eventBus.Emit(ctx, event.Event{- ID: answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,- Data: event.AgentFinalAnswerData{Content: tail},- })- }-- if !answerDoneEmitted {- e.eventBus.Emit(ctx, event.Event{- ID: answerID,- Type: event.EventAgentFinalAnswer,- SessionID: sessionID,- Data: event.AgentFinalAnswerData{- Content: "",- Done: true,- },- })- }-- // The synthesis call is often the largest of the turn — fold its usage- // into the turn aggregate like every ReAct round.- if llmResult.Usage != nil {- state.TurnUsage.Accumulate(*llmResult.Usage)- }+ _, tail := splitter.Flush()+ _ = e.eventBus.Emit(ctx, event.Event{+ ID: answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,+ Data: event.AgentFinalAnswerData{Content: terminalContent + tail, Done: true},+ })// Safety net: strip any residual <think> blocks that may have leaked throughfullAnswer := agenttools.StripThinkBlocks(llmResult.Content)@@ -151,11 +195,61 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(return nil}+// Measure the same handle-encoded conversation sent by streamLLMToEventBus,+// plus the runtime notice appended by the protocol adapter.+func (e *AgentEngine) finalAnswerInputTokens(messages []chat.Message, notice string) int {+ return e.tokenEstimator.EstimateMessages(e.modelContext.EncodeMessages(messages)) ++ e.tokenEstimator.EstimateMessage(&chat.Message{Role: "system", Content: notice})+}++func (e *AgentEngine) finalAnswerInputBudget() int {+ return max(e.config.MaxContextTokens-e.getCompletionTokenBudget()-contextSafetyTokens, 1)+}++func (e *AgentEngine) finalAnswerNeedsCompaction(messages []chat.Message, notice string) bool {+ return e.config.MaxContextTokens > 0 && e.finalAnswerInputTokens(messages, notice) > e.finalAnswerInputBudget()+}++// Reuse normal compaction and checkpoint persistence. A last tool result can+// exceed the entire window on its own; after summarizing older history, trim+// it to the space left by the fixed prompt, notice and completion budget.+func (e *AgentEngine) compactFinalAnswerContext(+ ctx context.Context, messages []chat.Message, round int, notice string, reason compaction.Reason,+) ([]chat.Message, bool) {+ if ctx.Err() != nil || e.config.MaxContextTokens <= 0 {+ return messages, false+ }+ before := e.finalAnswerInputTokens(messages, notice)+ compacted, changed := e.runCompaction(ctx, messages, round, reason)+ if ctx.Err() != nil {+ return messages, false+ }+ inputTokens := e.finalAnswerInputTokens(compacted, notice)+ if inputTokens > e.finalAnswerInputBudget() || (reason == compaction.ReasonOverflow && !changed) {+ toolTokens := 0+ for _, msg := range e.modelContext.EncodeMessages(compacted) {+ if msg.Role == "tool" {+ toolTokens += e.tokenEstimator.EstimateMessage(&msg)+ }+ }+ budget := min(toolResultBudget(e.config.MaxContextTokens),+ max(e.finalAnswerInputBudget()-(inputTokens-toolTokens), 1))+ var trimmed bool+ compacted, trimmed = trimToolResultsToBudget(compacted, e.tokenEstimator, budget)+ if trimmed {+ e.contextRewrites+++ logger.Infof(ctx, "[Agent][FinalAnswer] Trimmed tool results to %d tokens", budget)+ }+ }+ return compacted, e.finalAnswerInputTokens(compacted, notice) < before+}+// handleMaxIterations generates a final answer when the agent loop exhausted all iterations-// without the LLM producing a natural stop. It marks state.IsComplete = true.+// without the LLM producing a natural stop. Completion still persists the+// fallback and prior steps on failure, while the error remains observable.func (e *AgentEngine) handleMaxIterations(ctx context.Context, query string, state *types.AgentState, sessionID string, messages []chat.Message,-) {+) error {logger.Info(ctx, "Reached max iterations, generating final answer")common.PipelineWarn(ctx, "Agent", "max_iterations_reached", map[string]interface{}{"iterations": state.CurrentRound,@@ -169,8 +263,11 @@ func (e *AgentEngine) handleMaxIterations("error": err.Error(),})state.FinalAnswer = "Sorry, I was unable to generate a complete answer."+ state.IsComplete = true+ return fmt.Errorf("failed to synthesize final answer after max iterations: %w", err)}state.IsComplete = true+ return nil}// emitCompletionEvent emits the EventAgentComplete event with execution summary.diff --git a/internal/agent/finalize_test.go b/internal/agent/finalize_test.gonew file mode 100644index 000000000..be6258e1d--- /dev/null+++ b/internal/agent/finalize_test.go@@ -0,0 +1,586 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "testing"++ agenttoken "github.com/Tencent/WeKnora/internal/agent/token"+ agenttools "github.com/Tencent/WeKnora/internal/agent/tools"+ "github.com/Tencent/WeKnora/internal/event"+ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/api/anthropicmessages"+ "github.com/Tencent/WeKnora/internal/models/chat"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+)++// This fixture uses synthetic data only. No model service or deployment is needed.+type oversizedSynthesisChat struct {+ estimator *agenttoken.Estimator+ window int+ err error+ calls int+ oversized int+ prompt int+ output int+}++func (m *oversizedSynthesisChat) GetModelName() string { return "synthetic-test-model" }+func (m *oversizedSynthesisChat) GetModelID() string { return "synthetic-test-model" }+func (m *oversizedSynthesisChat) Chat(context.Context, []chat.Message, *chat.ChatOptions) (*types.ChatResponse, error) {+ return &types.ChatResponse{Content: "Short synthetic summary.", FinishReason: "stop"}, nil+}++func (m *oversizedSynthesisChat) ChatStream(+ _ context.Context, messages []chat.Message, opts *chat.ChatOptions,+) (<-chan types.StreamResponse, error) {+ m.calls+++ if m.err != nil {+ return nil, m.err+ }+ m.prompt = m.estimator.EstimateMessages(messages)+ m.output = max(opts.MaxTokens, opts.MaxCompletionTokens)+ if m.prompt+m.output > m.window {+ m.oversized+++ return nil, fmt.Errorf("context_length_exceeded: input=%d output=%d window=%d", m.prompt, m.output, m.window)+ }+ ch := make(chan types.StreamResponse, 1)+ ch <- types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Synthetic answer.", FinishReason: "stop", Done: true,+ }+ close(ch)+ return ch, nil+}++// Final synthesis must not emit a request it knows the provider will reject:+// when the estimated input already exceeds the context window, it should+// refuse before sending (or recover after a provider rejection).+func TestStreamFinalAnswer_RejectsOversizedInput(t *testing.T) {+ model := &oversizedSynthesisChat{window: 8192}+ engine := newTestEngine(t, model, withMaxContextTokens(8192), withMaxCompletionTokens(2048))+ model.estimator = engine.tokenEstimator+ messages := []chat.Message{+ {Role: "system", Content: "Use only the synthetic evidence."},+ {Role: "user", Content: "Summarize the evidence."},+ {Role: "assistant", ToolCalls: []chat.ToolCall{{+ ID: "synthetic-call", Type: "function",+ Function: chat.FunctionCall{Name: "synthetic_tool", Arguments: `{}`},+ }}},+ {+ Role: "tool", Name: "synthetic_tool", ToolCallID: "synthetic-call",+ Content: strings.Repeat("synthetic evidence ", 10000),+ },+ }+ state := &types.AgentState{}+ err := engine.streamFinalAnswerToEventBus(+ context.Background(), "Summarize the evidence.", state, "synthetic-session", messages)+ t.Logf("calls=%d prompt_tokens=%d completion_budget=%d window=%d err=%v",+ model.calls, model.prompt, model.output, model.window, err)+ require.True(t, model.oversized == 0 || (err == nil && model.calls > model.oversized),+ "final synthesis should reject oversized input before sending, or recover after provider rejection")+}++// A final-synthesis failure after the iteration budget is exhausted must stay+// observable by the caller: handleMaxIterations must propagate the error+// instead of swallowing it behind IsComplete=true and a nil error.+func TestHandleMaxIterations_PropagatesSynthesisError(t *testing.T) {+ want := errors.New("synthetic final-synthesis failure")+ model := &oversizedSynthesisChat{err: want}+ engine := newTestEngine(t, model, withMaxIterations(1))+ state := &types.AgentState{CurrentRound: 1}+ _, err := engine.executeLoop(context.Background(), state, "Synthetic task",+ emptyMessages(), nil, "synthetic-session", "synthetic-message")+ t.Logf("calls=%d complete=%v returned_error=%v final_answer=%q",+ model.calls, state.IsComplete, err, state.FinalAnswer)+ require.ErrorIs(t, err, want, "final-synthesis failures must remain observable by the caller")+}++// Compaction and final synthesis use the same model, but only synthesis carries+// a runtime notice. Keep the two call counts separate to bound recovery.+type finalSynthesisChat struct {+ mockChat+ summaries int+ finals [][]chat.Message+ summaryErr error+ onSummary func()+ synthesize func(context.Context, []chat.Message, *chat.ChatOptions) (<-chan types.StreamResponse, error)+}++func (m *finalSynthesisChat) ChatStream(+ ctx context.Context, messages []chat.Message, opts *chat.ChatOptions,+) (<-chan types.StreamResponse, error) {+ if len(opts.Tools) > 0 {+ return m.mockChat.ChatStream(ctx, messages, opts)+ }+ if opts.RuntimeNotice == "" {+ m.summaries+++ if m.onSummary != nil {+ m.onSummary()+ }+ if m.summaryErr != nil {+ return nil, m.summaryErr+ }+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "## Goal\nSummarize the synthetic evidence.",+ FinishReason: "stop", Done: true,+ }), nil+ }+ m.finals = append(m.finals, append([]chat.Message(nil), messages...))+ if m.synthesize != nil {+ return m.synthesize(ctx, messages, opts)+ }+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Recovered answer.", FinishReason: "stop", Done: true,+ }), nil+}++func finalSynthesisChunks(chunks ...types.StreamResponse) <-chan types.StreamResponse {+ ch := make(chan types.StreamResponse, len(chunks))+ for _, chunk := range chunks {+ ch <- chunk+ }+ close(ch)+ return ch+}++func finalSynthesisInputTokens(e *AgentEngine, messages []chat.Message, opts *chat.ChatOptions) int {+ return e.tokenEstimator.EstimateMessages(messages) + e.tokenEstimator.EstimateMessage(+ &chat.Message{Role: "system", Content: opts.RuntimeNotice},+ )+}++func TestFinalSynthesisCompactsBeforeSendingOversizedInput(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(24000), withMaxCompletionTokens(2048))+ sink := &recordingCheckpointSink{}+ engine.SetContextCheckpointSink(sink)+ messages := append(storedHistoryOverflow(), chat.Message{+ Role: "user", Content: "Latest correction: answer in Chinese using only the supplied evidence.",+ Images: []string{"https://example.com/correction.png"},+ })+ // The long tool transcript belongs to a completed stored turn. The latest+ // correction starts the live turn, so compaction can persist turn-c.+ for i := 5; i < len(messages)-1; i++ {+ messages[i].TurnID = "turn-c"+ }+ original, err := json.Marshal(messages)+ require.NoError(t, err)+ model.synthesize = func(+ _ context.Context, sent []chat.Message, opts *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ require.LessOrEqual(t, finalSynthesisInputTokens(engine, sent, opts)+opts.MaxCompletionTokens, 24000)+ require.Empty(t, opts.Tools)+ require.Equal(t, "none", opts.ToolChoice)+ require.Equal(t, messages[len(messages)-1], sent[len(sent)-1], "retain the latest correction and images")+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Recovered answer.",+ Done: true, FinishReason: "stop",+ }), nil+ }+ state := &types.AgentState{}+ require.NoError(t, engine.streamFinalAnswerToEventBus(t.Context(), "Summarize", state, "session", messages))+ require.Positive(t, model.summaries)+ require.Len(t, model.finals, 1)+ require.Equal(t, "Recovered answer.", state.FinalAnswer)+ require.Equal(t, []string{"turn-c"}, sink.turnIDs)+ after, err := json.Marshal(messages)+ require.NoError(t, err)+ require.JSONEq(t, string(original), string(after), "do not mutate the conversation saved by the caller")+}++func TestFinalSynthesisBoundsTheLastLargeToolResult(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(8192), withMaxCompletionTokens(2048))+ messages := []chat.Message{+ {Role: "system", Content: "Use only the evidence."},+ {Role: "user", Content: "Summarize."},+ {Role: "assistant", ToolCalls: []chat.ToolCall{{+ ID: "call-1", Type: "function",+ Function: chat.FunctionCall{Name: "synthetic_tool", Arguments: `{}`},+ }}},+ {+ Role: "tool", Name: "synthetic_tool", ToolCallID: "call-1",+ Content: strings.Repeat("synthetic evidence ", 10000),+ },+ }+ model.synthesize = func(+ _ context.Context, sent []chat.Message, opts *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ tokens := finalSynthesisInputTokens(engine, sent, opts)+ if tokens+opts.MaxCompletionTokens > 8192 {+ return nil, fmt.Errorf("context_length_exceeded: input=%d output=%d", tokens, opts.MaxCompletionTokens)+ }+ last := sent[len(sent)-1]+ require.Equal(t, "tool", last.Role)+ require.Equal(t, "call-1", last.ToolCallID)+ require.Equal(t, "call-1", sent[len(sent)-2].ToolCalls[0].ID)+ require.Contains(t, last.Content, "Tool result compacted")+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Bounded answer.", Done: true, FinishReason: "stop",+ }), nil+ }+ state := &types.AgentState{}+ require.NoError(t, engine.streamFinalAnswerToEventBus(t.Context(), "Summarize", state, "session", messages))+ require.Len(t, model.finals, 1, "the known oversized input must never be sent")+ require.Equal(t, "Bounded answer.", state.FinalAnswer)+ require.Equal(t, strings.Repeat("synthetic evidence ", 10000), messages[len(messages)-1].Content)+}++func TestFinalSynthesisRecoversProviderOverflowOnce(t *testing.T) {+ for _, repeated := range []bool{false, true} {+ t.Run(fmt.Sprintf("repeated=%v", repeated), func(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(64000), withMaxCompletionTokens(2048))+ // A previous ReAct round's recovery must not consume the final call's+ // own retry: the final transcript includes that round's tool results.+ engine.overflowRecovered = true+ want := errors.New("context_length_exceeded: provider tokenizer counted more input")+ model.synthesize = func(+ _ context.Context, _ []chat.Message, _ *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ if len(model.finals) == 1 || repeated {+ return nil, want+ }+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Recovered answer.",+ Done: true, FinishReason: "stop",+ }), nil+ }+ state := &types.AgentState{}+ err := engine.streamFinalAnswerToEventBus(+ t.Context(), "Summarize", state, "session", storedHistoryOverflow(),+ )+ if repeated {+ require.ErrorIs(t, err, want)+ require.Empty(t, state.FinalAnswer)+ } else {+ require.NoError(t, err)+ require.Equal(t, "Recovered answer.", state.FinalAnswer)+ }+ require.Len(t, model.finals, 2)+ require.Positive(t, model.summaries)+ require.Less(t, engine.tokenEstimator.EstimateMessages(model.finals[1]),+ engine.tokenEstimator.EstimateMessages(model.finals[0]))+ })+ }+}++func TestFinalSynthesisClearsPartialAnswerBeforeOverflowRetry(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(64000), withMaxCompletionTokens(2048))+ recorder := &truncationRecorder{}+ recorder.attach(engine.eventBus)+ model.synthesize = func(+ _ context.Context, _ []chat.Message, _ *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ if len(model.finals) == 1 {+ return finalSynthesisChunks(+ types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Content: "Discard this partial answer."},+ types.StreamResponse{+ ResponseType: types.ResponseTypeError,+ Content: "context_length_exceeded", Done: true,+ },+ ), nil+ }+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Recovered answer.",+ Done: true, FinishReason: "stop",+ }), nil+ }+ require.NoError(t, engine.streamFinalAnswerToEventBus(+ t.Context(), "Summarize", &types.AgentState{}, "session", storedHistoryOverflow(),+ ))+ var rendered string+ done, resets := 0, 0+ for _, evt := range recorder.snapshot() {+ if evt.Replace {+ rendered = ""+ resets+++ }+ rendered += evt.Content+ if evt.Done {+ done+++ }+ }+ require.Equal(t, "Recovered answer.", rendered)+ require.Equal(t, 1, resets)+ require.Equal(t, 1, done)+}++func TestFinalSynthesisRecoversContextLengthStopAndAccountsForBothAttempts(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(64000), withMaxCompletionTokens(2048))+ recorder := &truncationRecorder{}+ recorder.attach(engine.eventBus)+ model.synthesize = func(+ _ context.Context, _ []chat.Message, _ *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ if len(model.finals) == 1 {+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Unfinished answer.",+ FinishReason: "length", Done: true,+ Usage: &types.TokenUsage{PromptTokens: 63999, CompletionTokens: 1, TotalTokens: 64000},+ }), nil+ }+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Recovered answer.", FinishReason: "stop", Done: true,+ Usage: &types.TokenUsage{PromptTokens: 5000, CompletionTokens: 50, TotalTokens: 5050},+ }), nil+ }+ state := &types.AgentState{}+ require.NoError(t, engine.streamFinalAnswerToEventBus(+ t.Context(), "Summarize", state, "session", storedHistoryOverflow(),+ ))+ require.Len(t, model.finals, 2)+ require.Equal(t, "Recovered answer.", state.FinalAnswer)+ require.Equal(t, 69050, state.TurnUsage.TotalTokens)+ done := 0+ for _, evt := range recorder.snapshot() {+ require.NotContains(t, evt.Content, "Unfinished answer")+ if evt.Done {+ done+++ }+ }+ require.Equal(t, 1, done, "the rejected attempt must never close the answer")+}++func TestFinalSynthesisDoesNotRetryOrdinaryOutputTruncation(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(64000), withMaxCompletionTokens(2048))+ model.synthesize = func(+ _ context.Context, _ []chat.Message, _ *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "Answer cut off at its output limit.",+ FinishReason: "length", Done: true,+ Usage: &types.TokenUsage{PromptTokens: 5000, CompletionTokens: 2048, TotalTokens: 7048},+ }), nil+ }+ state := &types.AgentState{}+ require.NoError(t, engine.streamFinalAnswerToEventBus(t.Context(), "Summarize", state, "session", emptyMessages()))+ require.Len(t, model.finals, 1)+ require.Zero(t, model.summaries)+ require.Equal(t, "Answer cut off at its output limit.", state.FinalAnswer)+}++func TestFinalSynthesisRejectsUnshrinkableInput(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(8192), withMaxCompletionTokens(2048))+ messages := []chat.Message{{Role: "system", Content: strings.Repeat("fixed policy ", 10000)}}+ err := engine.streamFinalAnswerToEventBus(t.Context(), "Summarize", &types.AgentState{}, "session", messages)+ require.ErrorContains(t, err, "context window")+ require.Empty(t, model.finals)+ require.Zero(t, model.summaries)+}++func TestFinalSynthesisDoesNotRetryWithoutSmallerContext(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(8192))+ want := errors.New("context_length_exceeded")+ model.synthesize = func(+ context.Context, []chat.Message, *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ return nil, want+ }+ err := engine.streamFinalAnswerToEventBus(t.Context(), "Summarize", &types.AgentState{}, "session", emptyMessages())+ require.ErrorIs(t, err, want)+ require.Len(t, model.finals, 1)+ require.Zero(t, model.summaries)+}++func TestFinalSynthesisCancellationSkipsRecovery(t *testing.T) {+ for _, beforeCall := range []bool{false, true} {+ t.Run(fmt.Sprintf("before_call=%v", beforeCall), func(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(64000))+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ if beforeCall {+ cancel()+ }+ model.synthesize = func(+ context.Context, []chat.Message, *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ cancel()+ return nil, errors.New("context_length_exceeded")+ }+ err := engine.streamFinalAnswerToEventBus(+ ctx, "Summarize", &types.AgentState{}, "session", storedHistoryOverflow(),+ )+ require.ErrorIs(t, err, context.Canceled)+ require.Zero(t, model.summaries)+ if beforeCall {+ require.Empty(t, model.finals)+ } else {+ require.Len(t, model.finals, 1)+ }+ })+ }+}++func TestFinalSynthesisCancellationDuringCompactionSkipsModelCall(t *testing.T) {+ model := &finalSynthesisChat{summaryErr: context.Canceled}+ engine := newTestEngine(t, model, withMaxContextTokens(24000), withMaxCompletionTokens(2048))+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ model.onSummary = cancel+ err := engine.streamFinalAnswerToEventBus(+ ctx, "Summarize", &types.AgentState{}, "session", storedHistoryOverflow(),+ )+ require.ErrorIs(t, err, context.Canceled)+ require.Empty(t, model.finals)+}++func TestFinalSynthesisRecoversWhenSummarizerFails(t *testing.T) {+ model := &finalSynthesisChat{summaryErr: errors.New("summarizer unavailable")}+ engine := newTestEngine(t, model, withMaxContextTokens(24000), withMaxCompletionTokens(2048))+ model.synthesize = func(+ _ context.Context, sent []chat.Message, opts *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ require.LessOrEqual(t, finalSynthesisInputTokens(engine, sent, opts)+opts.MaxCompletionTokens, 24000)+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer,+ Content: "Recovered from bounded archive.", Done: true, FinishReason: "stop",+ }), nil+ }+ state := &types.AgentState{}+ require.NoError(t, engine.streamFinalAnswerToEventBus(+ t.Context(), "Summarize", state, "session", storedHistoryOverflow(),+ ))+ require.Positive(t, model.summaries)+ require.LessOrEqual(t, model.summaries, 4, "at most two attempts each for history and turn-prefix summaries")+ require.Len(t, model.finals, 1)+ require.Equal(t, "Recovered from bounded archive.", state.FinalAnswer)+}++type finalSynthesisLargeTool struct {+ *countingTool+ output string+}++func (tool *finalSynthesisLargeTool) Execute(context.Context, json.RawMessage) (*types.ToolResult, error) {+ tool.calls+++ return &types.ToolResult{Success: true, Output: tool.output}, nil+}++func TestMaxIterationsCompactsFinalAnswerWithoutReplayingTools(t *testing.T) {+ model := &finalSynthesisChat{mockChat: mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{{+ ResponseType: types.ResponseTypeAnswer, FinishReason: "tool_calls", Done: true,+ ToolCalls: []types.LLMToolCall{{ID: "call-once", Type: "function", Function: types.FunctionCall{+ Name: "synthetic_tool", Arguments: `{}`,+ }}},+ }}}}}}+ engine := newTestEngine(t, model, withMaxIterations(1), withMaxContextTokens(8192), withMaxCompletionTokens(2048))+ engine.toolRegistry = agenttools.NewToolRegistry()+ tool := &finalSynthesisLargeTool{+ countingTool: newCountingTool("synthetic_tool"),+ output: strings.Repeat("synthetic evidence ", 10000),+ }+ engine.toolRegistry.RegisterTool(tool)+ var recordedOutput string+ engine.eventBus.On(event.EventAgentToolResult, func(_ context.Context, evt event.Event) error {+ recordedOutput = evt.Data.(event.AgentToolResultData).Output+ return nil+ })+ model.synthesize = func(+ _ context.Context, sent []chat.Message, opts *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ require.LessOrEqual(t, finalSynthesisInputTokens(engine, sent, opts)+opts.MaxCompletionTokens, 8192)+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer,+ Content: "Final answer after tool execution.", Done: true, FinishReason: "stop",+ }), nil+ }+ state := &types.AgentState{}+ _, err := engine.executeLoop(+ t.Context(), state, "Summarize", emptyMessages(), engine.buildToolsForLLM(), "session", "message",+ )+ require.NoError(t, err)+ require.Equal(t, 1, tool.calls)+ require.Len(t, model.finals, 1)+ require.True(t, state.IsComplete)+ require.Equal(t, "Final answer after tool execution.", state.FinalAnswer)+ require.Len(t, state.RoundSteps, 1)+ require.NotEmpty(t, recordedOutput)+ require.Equal(t, recordedOutput, state.RoundSteps[0].ToolCalls[0].Result.Output,+ "synthesis trimming must not alter the tool result already emitted and retained for persistence")+ require.Contains(t, model.finals[0][len(model.finals[0])-1].Content, "Tool result compacted")+}++func TestFinalSynthesisDoesNotDoubleCountAnthropicThinking(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxContextTokens(32768), withMaxCompletionTokens(4096))+ thinking := strings.Repeat("synthetic reasoning ", 10000)+ blocks, err := json.Marshal([]map[string]string{+ {"type": "thinking", "thinking": thinking, "signature": "synthetic-signature"},+ })+ require.NoError(t, err)+ messages := []chat.Message{+ {Role: "system", Content: "Use the evidence."},+ {Role: "user", Content: "Answer briefly."},+ {+ Role: "assistant", ReasoningContent: thinking,+ ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "synthetic-signature"),+ ReasoningMetadata: types.ProviderMetadata{anthropicmessages.MetadataThinkingBlocks: blocks},+ ToolCalls: []chat.ToolCall{{+ ID: "call-1", Type: "function",+ Function: chat.FunctionCall{Name: "synthetic_tool", Arguments: `{}`},+ }},+ },+ {Role: "tool", ToolCallID: "call-1", Name: "synthetic_tool", Content: "Successful tool result."},+ }+ client := anthropicmessages.New(anthropicmessages.Config{+ Endpoint: api.Endpoint{Model: "synthetic-anthropic"}, Settings: api.DefaultAnthropicMessages(),+ })+ model.synthesize = func(+ _ context.Context, sent []chat.Message, opts *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ body, err := client.BuildRequestBody(sent, opts, true)+ require.NoError(t, err)+ wire, err := json.Marshal(body)+ require.NoError(t, err)+ require.Less(t, engine.tokenEstimator.EstimateString(string(wire))+opts.MaxCompletionTokens, 32768)+ require.Equal(t, 4096, opts.MaxCompletionTokens, "duplicate display fields must not consume the output budget")+ return finalSynthesisChunks(types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer, Content: "OK", Done: true, FinishReason: "stop",+ }), nil+ }+ require.NoError(t, engine.streamFinalAnswerToEventBus(+ t.Context(), "Answer briefly", &types.AgentState{}, "session", messages,+ ))+ require.Zero(t, model.summaries, "a request that fits must retain the signed thinking without compaction")+ require.Len(t, model.finals, 1)+}++func TestMaxIterationsPropagatesSynthesisFailureAndStillCompletes(t *testing.T) {+ model := &finalSynthesisChat{}+ engine := newTestEngine(t, model, withMaxIterations(1))+ want := errors.New("synthetic synthesis failure")+ model.synthesize = func(+ context.Context, []chat.Message, *chat.ChatOptions,+ ) (<-chan types.StreamResponse, error) {+ return nil, want+ }+ var completions []event.AgentCompleteData+ engine.eventBus.On(event.EventAgentComplete, func(_ context.Context, evt event.Event) error {+ completions = append(completions, evt.Data.(event.AgentCompleteData))+ return nil+ })+ state := &types.AgentState{+ CurrentRound: 1,+ RoundSteps: []types.AgentStep{{Iteration: 0, Thought: "Collected evidence"}},+ }+ _, err := engine.executeLoop(t.Context(), state, "Summarize", emptyMessages(), nil, "session", "message")+ require.ErrorIs(t, err, want)+ require.Len(t, model.finals, 1)+ require.True(t, state.IsComplete)+ require.Equal(t, "Sorry, I was unable to generate a complete answer.", state.FinalAnswer)+ require.Len(t, completions, 1)+ require.Equal(t, state.FinalAnswer, completions[0].FinalAnswer)+ require.Equal(t, state.RoundSteps, completions[0].AgentSteps)+ require.Equal(t, "message", completions[0].MessageID)+}diff --git a/internal/agent/token/estimator.go b/internal/agent/token/estimator.goindex eb489f734..ea7e13e54 100644--- a/internal/agent/token/estimator.go+++ b/internal/agent/token/estimator.go@@ -152,8 +152,7 @@ func (e *Estimator) EstimateMessage(msg *chat.Message) int {tokens += e.EstimateString(msg.Content)tokens += e.EstimateString(msg.Name)tokens += e.EstimateString(msg.ToolCallID)- tokens += e.EstimateString(msg.ReasoningContent)- tokens += e.EstimateReasoningArtifacts(msg)+ tokens += e.EstimateReasoning(msg)tokens += e.estimateImageParts(msg)for _, tc := range msg.ToolCalls {@@ -166,11 +165,40 @@ func (e *Estimator) EstimateMessage(msg *chat.Message) int {return tokens}+// EstimateReasoning counts the reasoning text and provider state that are+// replayed, excluding legacy display fields superseded by canonical metadata.+func (e *Estimator) EstimateReasoning(msg *chat.Message) int {+ text, artifacts := e.estimateReasoning(msg)+ return text + artifacts+}+// EstimateReasoningArtifacts counts the opaque provider state replayed with an// assistant turn. The signature carries a protocol tag that is stripped before// it goes out, so only the payload after the tag is billed; the metadata is// sent as-is, one JSON value per namespace key.func (e *Estimator) EstimateReasoningArtifacts(msg *chat.Message) int {+ _, artifacts := e.estimateReasoning(msg)+ return artifacts+}++func (e *Estimator) estimateReasoning(msg *chat.Message) (text, artifacts int) {+ // Anthropic stores the same signed thinking in both display fields and+ // canonical blocks. replayThinkingBlocks sends only the canonical blocks+ // when they decode successfully, including when the list is empty. Match+ // that precedence; malformed metadata still falls back to legacy fields.+ if raw := msg.ReasoningMetadata["anthropic_thinking_blocks"]; len(raw) > 0 {+ var blocks []struct {+ Type, Thinking, Signature, Data string+ }+ if json.Unmarshal(raw, &blocks) == nil {+ for key, value := range msg.ReasoningMetadata {+ if key != "anthropic_redacted_thinking" {+ artifacts += e.EstimateString(key) + e.EstimateString(string(value))+ }+ }+ return 0, artifacts+ }+ }tokens := 0if sig := msg.ReasoningSignature; sig != "" {if _, payload, found := strings.Cut(sig, ":"); found {@@ -179,7 +207,7 @@ func (e *Estimator) EstimateReasoningArtifacts(msg *chat.Message) int {tokens += e.EstimateString(sig)}tokens += e.estimateProviderMetadata(msg.ReasoningMetadata)- return tokens+ return e.EstimateString(msg.ReasoningContent), tokens}// estimateProviderMetadata counts one opaque provider-state map, one JSONdiff --git a/internal/agent/token/reasoning_artifacts_test.go b/internal/agent/token/reasoning_artifacts_test.goindex 3627e33e4..e29d81998 100644--- a/internal/agent/token/reasoning_artifacts_test.go+++ b/internal/agent/token/reasoning_artifacts_test.go@@ -7,8 +7,54 @@ import ("github.com/Tencent/WeKnora/internal/models/chat""github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require")+func TestEstimateMessageCountsAnthropicThinkingOnce(t *testing.T) {+ est, err := NewEstimator()+ require.NoError(t, err)+ thinking := strings.Repeat("synthetic reasoning ", 1000)+ signature := strings.Repeat("c2ln", 200)+ blocks, err := json.Marshal([]map[string]string{+ {"type": "thinking", "thinking": thinking, "signature": signature},+ {"type": "redacted_thinking", "data": "opaque-block"},+ })+ require.NoError(t, err)+ canonical := chat.Message{Role: "assistant", ReasoningMetadata: types.ProviderMetadata{+ "anthropic_thinking_blocks": blocks,+ }}+ duplicated := canonical+ duplicated.ReasoningContent = thinking+ duplicated.ReasoningSignature = "anthropic-messages:" + signature+ duplicated.ReasoningMetadata = types.ProviderMetadata{+ "anthropic_thinking_blocks": blocks,+ "anthropic_redacted_thinking": json.RawMessage(`["opaque-block"]`),+ }+ require.Equal(t, est.EstimateMessage(&canonical), est.EstimateMessage(&duplicated),+ "the provider replays the canonical blocks instead of the legacy display fields")+ require.Equal(t, est.EstimateReasoningArtifacts(&canonical), est.EstimateReasoningArtifacts(&duplicated))+ require.Greater(t, est.EstimateMessage(&duplicated), est.EstimateString(thinking),+ "the signed thinking and opaque artifacts must still be counted")+}++func TestEstimateMessageInvalidAnthropicMetadataKeepsLegacyReasoning(t *testing.T) {+ est, err := NewEstimator()+ require.NoError(t, err)+ for _, raw := range []string{`{}`, `[{"thinking":42}]`, `invalid`} {+ t.Run(raw, func(t *testing.T) {+ plain := chat.Message{Role: "assistant", ReasoningMetadata: types.ProviderMetadata{+ "anthropic_thinking_blocks": json.RawMessage(raw),+ }}+ legacy := plain+ legacy.ReasoningContent = strings.Repeat("legacy reasoning ", 100)+ legacy.ReasoningSignature = "anthropic-messages:signature"+ require.Equal(t, est.EstimateString(legacy.ReasoningContent)+est.EstimateString("signature"),+ est.EstimateMessage(&legacy)-est.EstimateMessage(&plain),+ "malformed canonical metadata falls back to the legacy fields on the wire")+ })+ }+}+// TestEstimateMessageCountsReasoningArtifacts pins the fix for the compaction// trigger under-measuring replayed assistant turns. An OpenAI Responses// encrypted reasoning item or an Anthropic signature rides on every replayed