From f97be4e553c313330f2ce9ac23decba97990a43e Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 31 Aug 2026 20:49:01 +0800 Subject: [PATCH] fix: preserve output-loop code across audits and SSE --- .../internal/pkg/neterror/classify_test.go | 6 ++++ .../transport/http/inference/handler.go | 6 +++- .../transport/http/inference/handler_test.go | 28 ++++++++++++++++++- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/backend/internal/pkg/neterror/classify_test.go b/backend/internal/pkg/neterror/classify_test.go index 664e74a5..5c1cbd98 100644 --- a/backend/internal/pkg/neterror/classify_test.go +++ b/backend/internal/pkg/neterror/classify_test.go @@ -58,6 +58,12 @@ func TestIsUpstreamResponseEmpty(t *testing.T) { } } +func TestIsUpstreamOutputLoop(t *testing.T) { + if !IsUpstreamOutputLoop(fmt.Errorf("read body: %w", ErrUpstreamOutputLoop)) || IsUpstreamOutputLoop(io.EOF) { + t.Fatal("output-loop sentinel classification failed") + } +} + func TestIsClientRequestCancel(t *testing.T) { idleCtx, idleCancel := context.WithCancelCause(context.Background()) idleCancel(ErrUpstreamStreamIdleTimeout) diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 875755c0..563c9eaa 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1536,9 +1536,13 @@ func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetad } return []byte("event: response.failed\ndata: " + string(payload) + "\n\n") case streamProtocolAnthropic: + anthropicMessage := message + if code == "upstream_output_loop" { + anthropicMessage = code + ": " + message + } payload, err := json.Marshal(map[string]any{ "type": "error", - "error": map[string]any{"type": "api_error", "message": message}, + "error": map[string]any{"type": "api_error", "message": anthropicMessage}, }) if err != nil { return nil diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index a577c1e3..4b056dcd 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -1056,6 +1056,10 @@ func TestClassifyCopyErrorDistinguishesClientFromUpstream(t *testing.T) { if got := classifyCopyError(idle, idleErr); got != "upstream_stream_idle_timeout" { t.Fatalf("idle timeout = %q", got) } + loopErr := fmt.Errorf("%w: %w", errUpstreamStreamRead, neterror.ErrUpstreamOutputLoop) + if got := classifyCopyError(context.Background(), loopErr); got != "upstream_output_loop" { + t.Fatalf("output loop = %q", got) + } } func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) { @@ -1096,7 +1100,7 @@ func TestCopyStreamWritesTerminalOnOutputLoop(t *testing.T) { }{ {name: "chat", protocol: streamProtocolChat, want: []string{`"code":"upstream_output_loop"`, "data: [DONE]"}}, {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.failed"`, `"code":"server_error"`, `"message":"upstream_output_loop:`, `"status":"failed"`}}, - {name: "anthropic", protocol: streamProtocolAnthropic, want: []string{`"type":"error"`, "上游输出陷入循环"}}, + {name: "anthropic", protocol: streamProtocolAnthropic, want: []string{`"type":"error"`, `"message":"upstream_output_loop: 上游输出陷入循环"`}}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -1640,6 +1644,28 @@ func TestWriteResultUpstreamCutStaysUpstreamInterrupted(t *testing.T) { } } +func TestWriteResultOutputLoopFinalizesDistinctCode(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(nil, nil, 1<<20) + var finalCode string + result := &gateway.Result{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(&outputLoopErrorReader{}), + Finalize: func(_ gateway.Usage, _, code string) { finalCode = code }, + } + router := gin.New() + router.POST("/", func(c *gin.Context) { + handler.writeResult(c, result, true, streamProtocolResponses) + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/", nil)) + if recorder.Code != http.StatusOK || finalCode != "upstream_output_loop" || !strings.Contains(recorder.Body.String(), `"message":"upstream_output_loop:`) { + t.Fatalf("status=%d finalize=%q body=%q", recorder.Code, finalCode, recorder.Body.String()) + } +} + func TestProjectStreamFailureDiagnosticBoundsErrorMessage(t *testing.T) { diagnostic := projectStreamFailureDiagnostic([]byte(`{"type":"error","error":{"code":"server_error","message":"` + strings.Repeat("错误", maxStreamFailureDiagnosticBytes) + `"},"output":"must-not-be-audited"}`)) if !diagnostic.BodyTruncated || len(diagnostic.Body) > maxStreamFailureDiagnosticBytes || len(diagnostic.Body) == 0 || !utf8.Valid(diagnostic.Body) || strings.Contains(string(diagnostic.Body), "must-not-be-audited") {