fix(llm): treat cut-off streams as broken and tighten LLM retries

A stream body that ran out without a finish reason (a proxy cutting the
connection) was closed as a clean stop on the Completions, Responses and
Gemini paths, so a half-written answer was stored as complete. It is now
marked incomplete, as the Anthropic path already did, and both the chat
pipeline and the agent treat an incomplete answer as a stream error.

Retry classification checks typed HTTP/transport errors first and matches
status codes as whole numbers, so "max_tokens 5000" no longer reads as a
500. The retry backoff returns as soon as the turn is cancelled.
main
wizardchen 2026-09-25 14:44:14 +08:00 committed by lyingbug
parent ef6f28c1ca
commit 8356742dd5
13 changed files with 256 additions and 12 deletions

View File

@ -1,13 +1,19 @@
package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/agent/compaction"
"github.com/Tencent/WeKnora/internal/browserskill"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/types"
"github.com/google/uuid"
)
@ -91,24 +97,46 @@ func toolExecutionTimeout(toolName string, arguments ...string) time.Duration {
return defaultToolExecTimeout
}
// transientErrorMarkers are substrings that indicate a transient (retryable) error.
// transientErrorMarkers are substrings that indicate a transient (retryable)
// error in a message that lost its type on the way here: stream failures reach
// the agent as text carried on an error chunk.
var transientErrorMarkers = []string{
"429", "rate limit",
"500", "502", "503", "504",
"rate limit",
"overloaded", "timeout", "timed out",
"connection", "server error", "temporarily unavailable",
// A broken or silent stream is worth one more attempt: the round produced
// no usable turn, and the alternative is ending the conversation on a
// partial response.
"deadline exceeded", "stalled",
"deadline exceeded", "stalled", "unexpected eof",
strings.ToLower(types.StreamEndedEarlyError),
}
// transientStatusPattern matches a retryable HTTP status as a whole number, so
// "max_tokens 5000" or a request id with 429 inside it does not read as one.
var transientStatusPattern = regexp.MustCompile(`\b(408|429|500|502|503|504|529)\b`)
// isTransientError checks whether an error is likely transient and worth retrying.
func isTransientError(err error) bool {
if err == nil {
if err == nil || errors.Is(err, context.Canceled) {
return false
}
// Typed errors decide on their own: a 400 whose body happens to mention
// "timeout" or "500" is still the same bad request on every retry.
var httpErr *api.HTTPError
if errors.As(err, &httpErr) {
code := httpErr.StatusCode
return code == http.StatusRequestTimeout || code == http.StatusTooManyRequests ||
code >= http.StatusInternalServerError
}
var transportErr *api.TransportError
if errors.As(err, &transportErr) || errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, io.ErrUnexpectedEOF) {
return true
}
errStr := strings.ToLower(err.Error())
if transientStatusPattern.MatchString(errStr) {
return true
}
for _, marker := range transientErrorMarkers {
if strings.Contains(errStr, marker) {
return true

View File

@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"sync"
"testing"
@ -13,6 +14,7 @@ import (
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/modelcontext"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
@ -1114,3 +1116,42 @@ func TestStreamFinalAnswerToEventBus_EmitsDoneWhenProviderEndsWithEmptyChunk(t *
"a decoder may hold a short suffix until Done to rule out a split model handle")
assert.Equal(t, "final answer", state.FinalAnswer)
}
func TestIsTransientErrorClassification(t *testing.T) {
for _, tc := range []struct {
name string
err error
want bool
}{
{"rate limited", &api.HTTPError{StatusCode: 429}, true},
{"server error", fmt.Errorf("chat: %w", &api.HTTPError{StatusCode: 503}), true},
{
"bad request mentioning a status",
&api.HTTPError{StatusCode: 400, Body: "max_tokens 5000 > 500 timeout"}, false,
},
{"transport", &api.TransportError{Op: "send request", Err: errors.New("dial tcp: refused")}, true},
{"unexpected eof", fmt.Errorf("read: %w", io.ErrUnexpectedEOF), true},
{"user stop", fmt.Errorf("round: %w", context.Canceled), false},
{"stream text with status", errors.New("LLM stream error: upstream returned 502"), true},
{"stream text with longer number", errors.New("LLM stream error: max_tokens must be <= 5000"), false},
{"stream ended early", fmt.Errorf("LLM stream error: %s", types.StreamEndedEarlyError), true},
{"invalid key", errors.New("LLM stream error: invalid api key"), false},
} {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, isTransientError(tc.err))
})
}
}
func TestStreamLLMIncompleteFinishIsAStreamError(t *testing.T) {
model := &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{
{ResponseType: types.ResponseTypeAnswer, Content: "partial"},
{ResponseType: types.ResponseTypeAnswer, Done: true, FinishReason: types.FinishReasonIncomplete},
}}}}
engine := newTestEngine(t, model)
_, err := engine.streamLLMToEventBus(context.Background(), nil, nil, nil)
require.Error(t, err, "a stream cut before its finish reason is not a completed turn")
require.True(t, isTransientError(err))
}

View File

@ -184,6 +184,12 @@ func (e *AgentEngine) streamLLMToEventBus(
if stalled.Load() {
result.StreamError = fmt.Sprintf("LLM stream stalled: no output for %s", stallTimeout)
}
// The provider layer closes a body that ran out without a finish reason
// as an incomplete answer rather than an error chunk; for a round that is
// the same broken stream and goes down the same retry path.
if result.StreamError == "" && result.FinishReason == types.FinishReasonIncomplete {
result.StreamError = types.StreamEndedEarlyError
}
// Stream diagnostic summary: helps identify non-streaming patterns
streamDuration := time.Duration(0)
@ -568,7 +574,15 @@ func (e *AgentEngine) callLLMWithRetry(
retryDelay := time.Duration(retry) * time.Second
logger.Warnf(ctx, "[Agent][Round-%d] LLM transient error (attempt %d/%d), retrying in %v: %v",
round, retry, maxLLMRetries, retryDelay, err)
time.Sleep(retryDelay)
// A stop pressed during the backoff ends the turn now rather than
// after the delay and one more doomed request.
select {
case <-ctx.Done():
case <-time.After(retryDelay):
}
if ctx.Err() != nil {
break
}
response, err = e.streamThinkingToEventBus(ctx, messages, tools, iteration, sessionID)
if err == nil || !isTransientError(err) {

View File

@ -193,6 +193,14 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
return
}
// A stream that stopped without a finish reason is a broken
// one, not a short answer: report it the way a read error is
// reported instead of closing the answer as complete.
if response.ResponseType == types.ResponseTypeAnswer && response.Done &&
response.FinishReason == types.FinishReasonIncomplete {
response.ResponseType = types.ResponseTypeError
response.Content = types.StreamEndedEarlyError
}
if response.ResponseType == types.ResponseTypeError {
pipelineError(ctx, "Stream", "stream_error", map[string]interface{}{
"session_id": chatManage.SessionID,

View File

@ -249,3 +249,36 @@ func TestStreamLeavesEmptyNaturalStopUnchanged(t *testing.T) {
}, 2*time.Second, 5*time.Millisecond)
require.Equal(t, []event.AgentFinalAnswerData{{Done: true}}, bus.finalAnswerEvents())
}
func TestStreamReportsIncompleteAsError(t *testing.T) {
bus := &syncEventBus{}
model := &openStreamChat{closeStream: true, chunks: []types.StreamResponse{
{ResponseType: types.ResponseTypeAnswer, Content: "partial"},
{ResponseType: types.ResponseTypeAnswer, Done: true, FinishReason: types.FinishReasonIncomplete},
}}
chatManage := &types.ChatManage{}
chatManage.SessionID = "sess-incomplete"
chatManage.EventBus = bus
plugin := &PluginChatCompletionStream{modelService: &stubModelService{model: model}}
require.Nil(t, plugin.OnEvent(
context.Background(), types.CHAT_COMPLETION_STREAM, chatManage,
func() *PluginError { return nil },
))
errorMessage := func() string {
bus.mu.Lock()
defer bus.mu.Unlock()
for _, evt := range bus.events {
if data, ok := evt.Data.(event.ErrorData); ok {
return data.Error
}
}
return ""
}
require.Eventually(t, func() bool { return errorMessage() != "" }, 2*time.Second, 5*time.Millisecond)
require.Equal(t, types.StreamEndedEarlyError, errorMessage())
for _, answer := range bus.finalAnswerEvents() {
require.False(t, answer.Done, "a cut-off stream must not close the answer as complete")
}
}

View File

@ -347,7 +347,7 @@ func (c *Client) processStream(
event, err := reader.ReadEvent()
if err != nil {
if err == io.EOF {
assembler.End(ch)
assembler.EndAtEOF(ch)
} else {
assembler.Fail(ch, err)
}

View File

@ -697,3 +697,35 @@ func TestChatStreamSurfacesPromptFeedbackBlock(t *testing.T) {
t.Fatal("blocked prompt did not produce an error chunk")
}
}
// Gemini streams end on EOF; the last candidate of a finished message carries
// a finishReason, so a body that stops without one was cut mid-answer.
func TestChatStreamEOFWithoutFinishReasonIsIncomplete(t *testing.T) {
for _, tc := range []struct {
name, body, want string
}{
{"cut off", `{"candidates":[{"content":{"parts":[{"text":"Hel"}]}}]}`, types.FinishReasonIncomplete},
{"finished", `{"candidates":[{"content":{"parts":[{"text":"Hello"}]},"finishReason":"STOP"}]}`, "stop"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("data: " + tc.body + "\n\n"))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatal(err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeAnswer || !last.Done || last.FinishReason != tc.want {
t.Fatalf("last event = %+v, want finish reason %q", last, tc.want)
}
})
}
}

View File

@ -305,12 +305,12 @@ func (c *Client) processStream(
reader := api.NewSSEReader(body)
var reasoningDetails []json.RawMessage
finish := func() {
finish := func(end func(chan<- types.StreamResponse)) {
if len(reasoningDetails) > 0 {
merged, _ := json.Marshal(reasoningDetails)
assembler.ReasoningMetadata = types.ProviderMetadata{metadataReasoningDetails: merged}
}
assembler.End(ch)
end(ch)
}
for {
@ -322,7 +322,7 @@ func (c *Client) processStream(
event, err := reader.ReadEvent()
if err != nil {
if err == io.EOF {
finish()
finish(assembler.EndAtEOF)
} else {
assembler.Fail(ch, err)
}
@ -332,7 +332,7 @@ func (c *Client) processStream(
continue
}
if event.Done {
finish()
finish(assembler.End)
return
}
if len(event.Data) == 0 {

View File

@ -688,3 +688,45 @@ func TestChatStream_MalformedToolCallFailsTheStream(t *testing.T) {
assert.True(t, sawError, "a dropped tool call must surface as an error")
assert.Equal(t, "ok", answer.String(), "decoding stops at the bad chunk")
}
// A body that runs out without [DONE] or any finish_reason is what a proxy
// cutting the connection mid-answer looks like; it must not read as a stop.
// [DONE] alone stays a clean end, since some vendors never send finish_reason.
func TestChatStream_EOFWithoutFinishReasonIsIncomplete(t *testing.T) {
cases := []struct {
name, tail, want string
}{
{"cut off", "", types.FinishReasonIncomplete},
{
"finish reason without DONE",
"data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", "stop",
},
{"DONE without finish reason", "data: [DONE]\n\n", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
head := "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\n"
_, _ = w.Write([]byte(head + tc.tail))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
Settings: api.DefaultOpenAICompletions(),
})
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.NoError(t, err)
var last types.StreamResponse
for chunk := range ch {
require.NotEqual(t, types.ResponseTypeError, chunk.ResponseType, chunk.Content)
if chunk.Done && chunk.ResponseType == types.ResponseTypeAnswer {
last = chunk
}
}
assert.Equal(t, tc.want, last.FinishReason)
})
}
}

View File

@ -370,9 +370,11 @@ func (c *Client) processStream(
reader := api.NewSSEReader(body)
st := &streamState{toolIndex: map[string]int{}, argsSeen: map[string]bool{}}
// response.completed / response.incomplete return before either caller,
// so reaching finish means the terminal event never arrived.
finish := func() {
assembler.ReasoningMetadata = reasoningMetadata(st.reasoningItems)
assembler.End(ch)
assembler.EndAtEOF(ch)
}
for {

View File

@ -674,3 +674,29 @@ func TestChatStreamMalformedOutputItemFailsTheStream(t *testing.T) {
t.Errorf("answer = %q, decoding must stop at the bad item", answer)
}
}
// response.completed is the only clean end of a Responses stream; a body that
// runs out before it was cut mid-answer and must not read as a stop.
func TestChatStreamEOFBeforeCompletedIsIncomplete(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
body := sseBody(`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"Hel"}`)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := newTestClient(t, server, false)
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeAnswer || !last.Done ||
last.FinishReason != types.FinishReasonIncomplete {
t.Fatalf("last event = %+v", last)
}
}

View File

@ -279,6 +279,19 @@ func (a *StreamAssembler) End(ch chan<- types.StreamResponse) {
})
}
// EndAtEOF closes a stream whose body simply ran out. A vendor that finished
// the message has reported a finish reason by then; without one the
// connection was most likely cut by a proxy or load balancer, and the answer
// is marked incomplete, as the Anthropic loop already does, instead of reaching
// the caller as a clean stop.
func (a *StreamAssembler) EndAtEOF(ch chan<- types.StreamResponse) {
if a.LastFinishReason == "" {
logger.Warnf(a.ctx, "Stream ended without a finish reason; marking the response incomplete")
a.LastFinishReason = types.FinishReasonIncomplete
}
a.End(ch)
}
// Fail emits the error chunk for a broken stream.
func (a *StreamAssembler) Fail(ch chan<- types.StreamResponse, err error) {
logger.Errorf(a.ctx, "Stream read error: %v (tool_calls_assembled=%d)", err, len(a.toolCallMap))

View File

@ -310,6 +310,11 @@ const (
// completed turn.
const FinishReasonIncomplete = "incomplete"
// StreamEndedEarlyError is what a consumer reports for an answer that arrived
// with FinishReasonIncomplete: the stream stopped before the provider said the
// message was finished, most often because a proxy cut the connection.
const StreamEndedEarlyError = "the model's response ended before it finished (connection interrupted)"
type StreamResponse struct {
ID string `json:"id"`
ResponseType ResponseType `json:"response_type"`