feat: terminate model output loops with split content/reasoning thresholds

A looping upstream stream burns account quota and the client context window
until the response budget is exhausted. Track consecutive identical deltas
and terminate the stream once a channel exceeds its ceiling.

Content and reasoning keep separate counters. high/xhigh effort reasoning
legitimately repeats the same short marker ("so", "hmm", "wait", list
bullets) far more often than visible output does, so a single shared
counter truncates valid deep-thinking responses. Reasoning is therefore
allowed a higher ceiling (256) than visible content (128).

The content ceiling also has to clear legitimate visible repetition:
markdown horizontal rules and ASCII table borders stream as long runs of
an identical single-character delta ("-", "=", "|").
This commit is contained in:
Sofwan committed 2026-08-22 03:12:50 +08:00
1 parent d6f6e9f5f8
commit 4f384fe4be
2 files changed
+212

No files matched your search

@@ -13,6 +13,17 @@ import (
const (
maxDeferredSearchTextBytes = 8 << 20
maxDeferredReasoningSummaryBytes = 8 << 20
// contentDoomLoopThreshold 连续重复同一可见内容增量时终止流。真正的
// 内容循环会消耗配额和客户端上下文,因此远低于推理上限;但仍需容纳
// 合法重复:markdown 分隔线与表格边框会以相同单字符增量("-"、"="、
// "|")连续输出。
contentDoomLoopThreshold = 128
// reasoningDoomLoopThreshold 高于内容阈值:high/xhigh 推理会大量重复
// 同一短标记("so"、"hmm"、"wait"、列表符号)。共用低阈值会过早终止
// 有效的深度推理响应。
reasoningDoomLoopThreshold = 256
)
// ConvertResponseStream 将 Responses SSE 转换为 Chat Completions 或 Anthropic Messages SSE。
@@ -68,6 +79,12 @@ type streamConverter struct {
stopFilter *anthropicStreamStopFilter
stopSequence string
refused bool
// 循环检测:可见内容与推理各自计数。推理合法地远比可见输出更常重复
// 同一短标记,共用一个计数器会过早终止有效的 high/xhigh 响应。
lastContentDelta string
contentRepeatCount int
lastReasonDelta string
reasonRepeatCount int
}
type streamTool struct {
@@ -426,6 +443,9 @@ func (c *streamConverter) reasoningSummaryDelta(itemID, delta string) error {
if delta == "" || !c.reasoningOutputEnabled() {
return nil
}
if err := c.trackReasoningRepeat(delta, "model reasoning summary loop detected"); err != nil {
return err
}
_, state := c.ensureReasoningState(itemID)
if state.done || state.rawSeen {
return nil
@@ -456,7 +476,27 @@ func (c *streamConverter) reasoningTextDelta(itemID, delta string) error {
return c.emitReasoningDelta(delta)
}
// trackReasoningRepeat 统计连续相同的推理增量,超过推理阈值则终止流。
func (c *streamConverter) trackReasoningRepeat(delta, message string) error {
if delta == "" {
return nil
}
if delta != c.lastReasonDelta {
c.lastReasonDelta = delta
c.reasonRepeatCount = 0
return nil
}
c.reasonRepeatCount++
if c.reasonRepeatCount >= reasoningDoomLoopThreshold {
return fmt.Errorf("%s (repeated delta %d times)", message, c.reasonRepeatCount)
}
return nil
}
func (c *streamConverter) emitReasoningDelta(delta string) error {
if err := c.trackReasoningRepeat(delta, "model reasoning loop detected"); err != nil {
return err
}
if c.operation == OperationChat {
return c.chatDelta(map[string]any{"reasoning_content": delta})
}
@@ -576,6 +616,19 @@ func (c *streamConverter) start() error {
}
func (c *streamConverter) textDelta(delta string) error {
// 循环检测:可见内容重复超过阈值时以错误终止流,避免循环耗尽账号配额
// 与客户端上下文窗口。推理增量使用独立且更高的计数器。
if delta != "" {
if delta == c.lastContentDelta {
c.contentRepeatCount++
if c.contentRepeatCount >= contentDoomLoopThreshold {
return fmt.Errorf("model output loop detected (repeated content delta %d times)", c.contentRepeatCount)
}
} else {
c.lastContentDelta = delta
c.contentRepeatCount = 0
}
}
if c.operation == OperationChat {
return c.textDeltaChat(delta)
}
@@ -0,0 +1,159 @@
package conversation
import (
"fmt"
"io"
"strings"
"testing"
)
// repeatSSE builds an SSE stream that emits the same delta count times using
// the given event name and payload template.
func repeatSSE(event, payloadTemplate string, count int, trailer ...string) string {
lines := []string{
`event: response.created`,
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6","status":"in_progress"}}`, "",
}
for i := 0; i < count; i++ {
lines = append(lines, "event: "+event, "data: "+payloadTemplate, "")
}
lines = append(lines, trailer...)
lines = append(lines,
`event: response.completed`,
`data: {"type":"response.completed","response":{"id":"resp_1","status":"completed"}}`, "", "")
return strings.Join(lines, "\n")
}
// A visible-content loop is a real quota burn: it must be terminated near the
// content threshold and must not be allowed to run to the reasoning threshold.
func TestConvertResponsesStreamTerminatesContentDoomLoop(t *testing.T) {
stream := repeatSSE("response.output_text.delta",
`{"type":"response.output_text.delta","delta":"loop"}`,
contentDoomLoopThreshold+8)
_, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
if err == nil {
t.Fatal("repeated visible content must terminate the stream")
}
if !strings.Contains(err.Error(), "model output loop detected") {
t.Fatalf("unexpected error: %v", err)
}
}
// Regression: high/xhigh effort reasoning legitimately repeats short tokens
// ("so", "hmm", "wait", bullet markers) far more often than visible output.
// A shared counter at the content threshold truncated valid deep-thinking
// answers, so reasoning must survive well past contentDoomLoopThreshold.
func TestConvertResponsesStreamKeepsRepeatedReasoningBelowThreshold(t *testing.T) {
for _, event := range []string{"response.reasoning_text.delta", "response.reasoning_summary_text.delta"} {
t.Run(event, func(t *testing.T) {
// Sit between the two ceilings: this run must be fatal for visible
// content but survivable for reasoning.
repeats := (contentDoomLoopThreshold + reasoningDoomLoopThreshold) / 2
if repeats <= contentDoomLoopThreshold || repeats >= reasoningDoomLoopThreshold {
t.Fatalf("test invariant broken: %d must sit between %d and %d",
repeats, contentDoomLoopThreshold, reasoningDoomLoopThreshold)
}
stream := repeatSSE(event,
fmt.Sprintf(`{"type":%q,"item_id":"rs_1","delta":"hmm"}`, event),
repeats,
`event: response.output_text.delta`,
`data: {"type":"response.output_text.delta","delta":"answer"}`, "")
converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
if err != nil {
t.Fatalf("deep reasoning must not be treated as a loop: %v", err)
}
if !strings.Contains(string(converted), `"content":"answer"`) {
t.Fatalf("visible answer was lost: %s", converted)
}
})
}
}
// The elevated reasoning threshold is a higher ceiling, not an exemption:
// a runaway reasoning loop still has to be terminated.
func TestConvertResponsesStreamTerminatesReasoningDoomLoop(t *testing.T) {
for _, testCase := range []struct {
event string
want string
}{
{"response.reasoning_text.delta", "model reasoning loop detected"},
{"response.reasoning_summary_text.delta", "model reasoning summary loop detected"},
} {
t.Run(testCase.event, func(t *testing.T) {
stream := repeatSSE(testCase.event,
fmt.Sprintf(`{"type":%q,"item_id":"rs_1","delta":"hmm"}`, testCase.event),
reasoningDoomLoopThreshold+8)
_, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
if err == nil {
t.Fatal("a runaway reasoning loop must still terminate the stream")
}
if !strings.Contains(err.Error(), testCase.want) {
t.Fatalf("unexpected error: %v", err)
}
})
}
}
// Legitimate visible repetition must survive: markdown horizontal rules and
// ASCII table borders stream as long runs of an identical single-character
// delta. This is why the content threshold cannot sit near typical rule width.
func TestConvertResponsesStreamKeepsMarkdownRuleAndTableBorders(t *testing.T) {
for _, testCase := range []struct{ name, delta string }{
{"horizontal rule", "-"},
{"table border", "="},
{"empty table cells", " | "},
} {
t.Run(testCase.name, func(t *testing.T) {
// A wide rule or table border comfortably exceeds 32 characters.
stream := repeatSSE("response.output_text.delta",
fmt.Sprintf(`{"type":"response.output_text.delta","delta":%q}`, testCase.delta),
80)
converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
if err != nil {
t.Fatalf("legitimate repeated formatting must not be treated as a loop: %v", err)
}
if !strings.Contains(string(converted), "data: [DONE]") {
t.Fatalf("stream did not complete: %s", converted)
}
})
}
}
// Counters are per-channel and reset on change, so alternating deltas and
// interleaved reasoning must never accumulate into a false positive.
func TestConvertResponsesStreamDoomLoopCountersResetAndStaySeparate(t *testing.T) {
lines := []string{
`event: response.created`,
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6","status":"in_progress"}}`, "",
}
// Alternating visible content never trips the content counter.
for i := 0; i < contentDoomLoopThreshold*2; i++ {
delta := "a"
if i%2 == 1 {
delta = "b"
}
lines = append(lines,
`event: response.output_text.delta`,
fmt.Sprintf(`data: {"type":"response.output_text.delta","delta":%q}`, delta), "")
}
// Reasoning repeats interleaved with distinct content must not share a
// counter: the reasoning run alone exceeds the content threshold.
for i := 0; i < contentDoomLoopThreshold*2; i++ {
lines = append(lines,
`event: response.reasoning_text.delta`,
`data: {"type":"response.reasoning_text.delta","item_id":"rs_1","delta":"hmm"}`, "",
`event: response.output_text.delta`,
fmt.Sprintf(`data: {"type":"response.output_text.delta","delta":"tick%d"}`, i), "")
}
lines = append(lines,
`event: response.completed`,
`data: {"type":"response.completed","response":{"id":"resp_1","status":"completed"}}`, "", "")
stream := strings.Join(lines, "\n")
converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
if err != nil {
t.Fatalf("alternating deltas must not be treated as a loop: %v", err)
}
if !strings.Contains(string(converted), "data: [DONE]") {
t.Fatalf("stream did not complete: %s", converted)
}
}