fix(audit): distinguish client vs upstream stream interrupts

After a 2xx SSE handoff, a client hangup is client_stream_interrupted and keeps the upstream status. upstream_stream_interrupted is only for an upstream cut. Pre-header 499 request_canceled is unchanged.
This commit is contained in:
buddhism5080 committed 2026-08-29 05:57:47 +08:00
1 parent 62d2775cb3
commit acc0fb5361
6 files changed
+147 -27

No files matched your search

@@ -205,16 +205,7 @@ func qualityPeekAbortError(ctx context.Context, err error) error {
// isClientRequestCancel reports a real client disconnect. Upstream idle
// timeouts cancel the same context and must not be classified as 499.
func isClientRequestCancel(ctx context.Context, err error) bool {
if neterrorpkg.IsUpstreamStreamIdleTimeout(err) {
return false
}
if ctx != nil && neterrorpkg.IsUpstreamStreamIdleTimeout(context.Cause(ctx)) {
return false
}
if ctx != nil && ctx.Err() != nil {
return true
}
return errors.Is(err, context.Canceled)
return neterrorpkg.IsClientRequestCancel(ctx, err)
}
// DecideQualityRetry caps withhold recovery at maxAttempts (default 6:
@@ -4651,6 +4651,7 @@ func TestAuditRequestSucceeded(t *testing.T) {
}{
{name: "2xx without error succeeds", statusCode: 200, errorCode: "", want: true},
{name: "2xx stream interruption fails", statusCode: 200, errorCode: "upstream_stream_interrupted", want: false},
{name: "2xx client stream interruption fails", statusCode: 200, errorCode: "client_stream_interrupted", want: false},
{name: "2xx stream incomplete fails", statusCode: 200, errorCode: "upstream_stream_incomplete", want: false},
{name: "2xx stream idle timeout fails", statusCode: 200, errorCode: "upstream_stream_idle_timeout", want: false},
{name: "any 2xx error fails", statusCode: 201, errorCode: "stream_interrupted", want: false},
@@ -4676,7 +4677,7 @@ func TestIsUpstreamStreamFailureIncludesIdleTimeout(t *testing.T) {
if !isUpstreamStreamFailure("upstream_response_empty") {
t.Fatal("empty non-streaming response must update account health after handoff")
}
if isUpstreamStreamFailure("") || isUpstreamStreamFailure("quality_degraded") {
if isUpstreamStreamFailure("") || isUpstreamStreamFailure("quality_degraded") || isUpstreamStreamFailure("client_stream_interrupted") || isUpstreamStreamFailure("request_canceled") {
t.Fatal("non-stream codes must not look like mid-stream failures")
}
}
+25
View File
@@ -1,6 +1,7 @@
package neterror
import (
"context"
"errors"
"net"
"strings"
@@ -70,3 +71,27 @@ func IdleTimeoutObservedData(err error) bool {
var idle *IdleTimeoutError
return errors.As(err, &idle) && idle.DataObserved
}
// IsClientRequestCancel reports a real client disconnect.
// Internal aborts (idle timeout, first-char timeout, …) cancel the same
// context with a cause other than context.Canceled and must not be treated
// as the client hanging up. Pre-header client cancel still maps to 499
// request_canceled; a 2xx stream copy uses client_stream_interrupted.
func IsClientRequestCancel(ctx context.Context, err error) bool {
if IsUpstreamStreamIdleTimeout(err) {
return false
}
if ctx != nil {
cause := context.Cause(ctx)
if IsUpstreamStreamIdleTimeout(cause) {
return false
}
if ctx.Err() != nil {
if cause != nil && !errors.Is(cause, context.Canceled) {
return false
}
return true
}
}
return errors.Is(err, context.Canceled)
}
@@ -57,3 +57,30 @@ func TestIsUpstreamResponseEmpty(t *testing.T) {
t.Fatal("empty response sentinel classification failed")
}
}
func TestIsClientRequestCancel(t *testing.T) {
idleCtx, idleCancel := context.WithCancelCause(context.Background())
idleCancel(ErrUpstreamStreamIdleTimeout)
if IsClientRequestCancel(idleCtx, context.Canceled) {
t.Fatal("idle timeout must not look like a client cancel")
}
if IsClientRequestCancel(context.Background(), ErrUpstreamStreamIdleTimeout) {
t.Fatal("idle timeout error must not look like a client cancel")
}
plain, cancel := context.WithCancel(context.Background())
cancel()
if !IsClientRequestCancel(plain, io.EOF) {
t.Fatal("canceled request context must be a client cancel")
}
if !IsClientRequestCancel(context.Background(), context.Canceled) {
t.Fatal("context.Canceled must be a client cancel")
}
if IsClientRequestCancel(context.Background(), io.EOF) {
t.Fatal("plain upstream EOF must not look like a client cancel")
}
internal, stop := context.WithCancelCause(context.Background())
stop(errors.New("upstream stream first char timeout"))
if IsClientRequestCancel(internal, context.Canceled) {
t.Fatal("internal cancel cause must not look like a client cancel")
}
}
@@ -3,6 +3,7 @@ package inference
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
@@ -1307,22 +1308,32 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
usage, responseID, err = metadata.Usage, metadata.ResponseID, copyErr
}
if err != nil {
switch {
case errors.Is(err, errResponseTransferLimit):
errorCode = "response_too_large"
case errors.Is(err, errUpstreamStreamFailed):
errorCode = "upstream_stream_error"
case errors.Is(err, errUpstreamStreamIncomplete):
errorCode = "upstream_stream_incomplete"
case errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout):
errorCode = "upstream_stream_idle_timeout"
case errors.Is(err, neterror.ErrUpstreamResponseEmpty):
errorCode = "upstream_response_empty"
case errors.Is(err, errUpstreamStreamRead):
errorCode = "upstream_stream_interrupted"
default:
errorCode = "stream_interrupted"
}
errorCode = classifyCopyError(c.Request.Context(), err)
}
}
func classifyCopyError(ctx context.Context, err error) string {
if err == nil {
return ""
}
if neterror.IsClientRequestCancel(ctx, err) {
return "client_stream_interrupted"
}
switch {
case errors.Is(err, errResponseTransferLimit):
return "response_too_large"
case errors.Is(err, errUpstreamStreamFailed):
return "upstream_stream_error"
case errors.Is(err, errUpstreamStreamIncomplete):
return "upstream_stream_incomplete"
case errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout):
return "upstream_stream_idle_timeout"
case errors.Is(err, neterror.ErrUpstreamResponseEmpty):
return "upstream_response_empty"
case errors.Is(err, errUpstreamStreamRead):
return "upstream_stream_interrupted"
default:
return "stream_interrupted"
}
}
@@ -2,6 +2,7 @@ package inference
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
@@ -1033,6 +1034,24 @@ func TestCopyStreamPreservesBufferedTailOnReadError(t *testing.T) {
}
}
func TestClassifyCopyErrorDistinguishesClientFromUpstream(t *testing.T) {
readErr := fmt.Errorf("%w: cut", errUpstreamStreamRead)
canceled, cancel := context.WithCancel(context.Background())
cancel()
if got := classifyCopyError(canceled, readErr); got != "client_stream_interrupted" {
t.Fatalf("client abort = %q", got)
}
if got := classifyCopyError(context.Background(), readErr); got != "upstream_stream_interrupted" {
t.Fatalf("upstream abort = %q", got)
}
idle, stop := context.WithCancelCause(context.Background())
stop(neterror.ErrUpstreamStreamIdleTimeout)
idleErr := fmt.Errorf("%w: %w", errUpstreamStreamRead, neterror.ErrUpstreamStreamIdleTimeout)
if got := classifyCopyError(idle, idleErr); got != "upstream_stream_idle_timeout" {
t.Fatalf("idle timeout = %q", got)
}
}
func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
@@ -1540,6 +1559,52 @@ func TestWriteResultRecordsStreamFailureDiagnostic(t *testing.T) {
}
}
func TestWriteResultClientAbortKeepsUpstreamStatus(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(&chunkErrorReader{data: []byte("data: {\"type\":\"response.created\"}\n\n")}),
Finalize: func(_ gateway.Usage, _, code string) { finalCode = code },
}
router := gin.New()
router.POST("/", func(c *gin.Context) {
handler.writeResult(c, result, true, streamProtocolResponses)
})
ctx, cancel := context.WithCancel(context.Background())
cancel()
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx))
if recorder.Code != http.StatusOK || finalCode != "client_stream_interrupted" {
t.Fatalf("status=%d finalize=%q body=%q", recorder.Code, finalCode, recorder.Body.String())
}
}
func TestWriteResultUpstreamCutStaysUpstreamInterrupted(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(&chunkErrorReader{data: []byte("data: {\"type\":\"response.created\"}\n\n")}),
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_stream_interrupted" {
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") {