From cbde784ed0d20fc796e410745963a5f0c88898ee Mon Sep 17 00:00:00 2001 From: debug-zhang <34176152+debug-zhang@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:31:31 +0800 Subject: [PATCH] fix(gateway): retry OpenAI upstream once after a pre-output connection reset Root cause: an upstream HTTP/2 connection multiplexes many in-flight requests. When a CDN resets that TCP connection, every stream multiplexed on it fails at once. Before any byte reached the client the gateway either returned 502 (reset before response headers) or a failover error that switched accounts (reset while reading the stream). The upstream keeps reading the request and bills it in full, so the request is charged upstream while the gateway records zero usage downstream. Change: Forward now treats a connection reset / unexpected EOF on an established upstream connection as a transport incident, not an account failure. When the client is still connected, the request body is replayable and this attempt wrote no client-visible byte (semantic output accounting; keepalive comments excluded), it rebuilds the request and replays it once on the same account. The replay never touches failover/account-health or sticky-session accounting; if it fails again the original failover error is returned and the existing path runs. Timeouts, context cancellation, client disconnects, dial failures and plugin hand-offs that may already have executed upstream are never replayed. Stream read errors expose a new ConnectionResetBeforeOutput marker so Forward can distinguish this window from other failovers. Tests: new openai_upstream_connection_reset_retry_test.go covers a reset before any client output (both the pre-header transport form and the stream-read form) retried once and succeeding, a second reset not starting a third attempt, a reset after client output not retried, timeout/cancel not retried, a non-replayable body not retried, the reset classifier, and the marker only being set before output. --- backend/internal/service/gateway_service.go | 6 + .../service/openai_gateway_forward.go | 34 ++ .../openai_gateway_response_handling.go | 7 +- .../openai_upstream_connection_reset.go | 134 +++++++ ...ai_upstream_connection_reset_retry_test.go | 337 ++++++++++++++++++ 5 files changed, 517 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/openai_upstream_connection_reset.go create mode 100644 backend/internal/service/openai_upstream_connection_reset_retry_test.go diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 425845b606..7fa89e8da3 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -806,6 +806,12 @@ type UpstreamFailoverError struct { ClientStatusCode int ClientMessage string StreamFailedFrame *OpenAIStreamFailedFrame // 触发本次 failover 的流内 failed/error 帧;耗尽时用于错误透传规则匹配 + // ConnectionResetBeforeOutput marks a connection reset/EOF observed after the + // upstream connection was established and before any byte reached the client. + // The request body is replayable, so it may be retried once on the same + // account over a fresh connection; the reset is not an account failure and + // must not trigger sticky-session escape or a schedule-result failure. + ConnectionResetBeforeOutput bool } func (e *UpstreamFailoverError) Error() string { diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index c0e6d13757..f78a66b3a8 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1058,6 +1058,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco httpInvalidEncryptedContentRetryTried := false compactModelFallbackRetried := false agentTaskRecoveryTried := false + // #8933: the whole request gets at most one extra attempt after an upstream + // connection reset that happened before any byte reached the client. The + // retry stays on the same account and is invisible to failover accounting. + connectionResetRetryUsed := false rejectedFieldRetryState := openAIResponsesRejectedFieldRetryStateForRequest(c, body) for { // Build upstream request @@ -1088,6 +1092,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // Send request upstreamStart := time.Now() + // Snapshot the client-visible byte count before the attempt so the reset + // retry below can prove this attempt wrote nothing (keepalive comments are + // excluded, matching the first-output failover accounting). + attemptOutputSizeBefore := OpenAICompactKeepaliveAdjustedWrittenSize(c) resp, err := s.doOpenAIUpstream(upstreamReq, proxyURL, account) SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) if headerGuard != nil && headerGuard.stopHeaderWait() { @@ -1108,6 +1116,17 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if headerGuard != nil { headerGuard.close() } + // #8933: a reset/EOF on the established upstream connection failed this + // request before the first client byte. The same account is still healthy + // (the shared connection died), so replay once on a fresh connection + // instead of turning the incident into an account failure / 502. + if !connectionResetRetryUsed && !openAIUpstreamRequestMayHaveReachedUpstreamViaPlugin(err) && openAIUpstreamResetRetryAllowed( + c, upstreamReq, ctx, attemptOutputSizeBefore, isOpenAIUpstreamConnectionResetError(err), + ) { + connectionResetRetryUsed = true + logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Retrying once on the same account after upstream connection reset before any client output (account: %s): %v", account.Name, err) + continue + } // Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to // a failover so the handler switches to a healthy account, and temporarily // unschedule the account on durable faults (e.g. rejected proxy credentials). @@ -1251,6 +1270,21 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if reqStream { streamResult, err := s.handleStreamingResponseWithReasoning(ctx, resp, c, account, startTime, originalModel, upstreamModel, reasoningEffortValue) if err != nil { + // #8933: the upstream stream was reset after the connection was + // established but before any byte reached the client. Replay once on + // the same account; the reset is a transport incident, not an account + // failure, so no failover/health bookkeeping is involved. + var resetFailoverErr *UpstreamFailoverError + if !connectionResetRetryUsed && errors.As(err, &resetFailoverErr) && openAIUpstreamResetRetryAllowed( + c, upstreamReq, ctx, attemptOutputSizeBefore, resetFailoverErr.ConnectionResetBeforeOutput, + ) { + connectionResetRetryUsed = true + if resp.Body != nil { + _ = resp.Body.Close() + } + logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Retrying once on the same account after upstream stream connection reset before any client output (account: %s): %v", account.Name, err) + continue + } if signal, ok := asOpenAICompactFallbackSignal(err); ok { if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, compactModelFallbackRetried, diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 72a0d4df69..e1addc17bc 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -474,7 +474,12 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. if errText := strings.TrimSpace(scanErr.Error()); errText != "" { msg += ": " + errText } - return resultWithUsage(), s.newOpenAIStreamFailoverError(c, account, false, upstreamRequestID, nil, msg), true + failoverErr := s.newOpenAIStreamFailoverError(c, account, false, upstreamRequestID, nil, msg) + // A reset/EOF before the first client byte is the shared-connection + // incident from #8933, not an account failure: Forward replays it once + // on the same account instead of switching accounts. + failoverErr.ConnectionResetBeforeOutput = isOpenAIUpstreamConnectionResetError(scanErr) + return resultWithUsage(), failoverErr, true } // 客户端已断开时,上游出错仅影响体验,不影响计费;返回已收集 usage if clientDisconnected { diff --git a/backend/internal/service/openai_upstream_connection_reset.go b/backend/internal/service/openai_upstream_connection_reset.go new file mode 100644 index 0000000000..19f2bc0e9d --- /dev/null +++ b/backend/internal/service/openai_upstream_connection_reset.go @@ -0,0 +1,134 @@ +package service + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "strings" + "syscall" + + "github.com/gin-gonic/gin" +) + +// Issue #8933: a CDN in front of the upstream can reset one HTTP/2 TCP +// connection, failing every request multiplexed on it. The upstream keeps +// reading the body and bills the request in full, while the gateway never +// receives the stream (or its usage). When the connection dies after it was +// established but before any byte reached the client, replaying the request +// once on the same account recovers the request without blaming the account: +// the shared connection failed, not the credential. + +// openAIUpstreamConnectionResetMarkers are transport error texts that mean the +// established connection or one of its streams was torn down, as opposed to a +// dial/proxy/timeout failure where replaying would only repeat the failure. +var openAIUpstreamConnectionResetMarkers = []string{ + "connection reset by peer", + "connection was forcibly closed", + "unexpected eof", + "broken pipe", + "http2: client connection lost", + "server sent goaway", + "stream error: stream id", +} + +// openAIUpstreamNonResetMarkers veto a replay even when the wrapped error text +// also carries a reset signature. Dial, DNS and deadline failures need +// different handling and must keep their existing classification. +var openAIUpstreamNonResetMarkers = []string{ + "connection refused", + "no route to host", + "network is unreachable", + "no such host", + "dial tcp", + "proxyconnect", + "timeout", + "deadline exceeded", + "context canceled", +} + +// isOpenAIUpstreamConnectionResetError reports whether err is a reset/EOF that +// happened on an already-established upstream connection. Timeouts, context +// cancellation and dialing failures are explicitly excluded: they are not the +// shared-connection incident this retry is meant to absorb. +func isOpenAIUpstreamConnectionResetError(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return false + } + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + return false + } + // A reset during the TCP/TLS handshake belongs to dialing, not to an + // established connection: nothing was sent upstream yet, so the normal + // reachability handling must own it. + var opErr *net.OpError + if errors.As(err, &opErr) && opErr.Op == "dial" { + return false + } + if errors.Is(err, syscall.ECONNRESET) || + errors.Is(err, syscall.ECONNABORTED) || + errors.Is(err, syscall.EPIPE) || + errors.Is(err, io.ErrUnexpectedEOF) || + errors.Is(err, io.EOF) { + return true + } + lower := strings.ToLower(strings.TrimSpace(err.Error())) + for _, marker := range openAIUpstreamNonResetMarkers { + if strings.Contains(lower, marker) { + return false + } + } + for _, marker := range openAIUpstreamConnectionResetMarkers { + if strings.Contains(lower, marker) { + return true + } + } + return false +} + +// openAIUpstreamRequestMayHaveReachedUpstreamViaPlugin reports a plugin hand-off +// that may already have executed upstream. Replaying it could duplicate side +// effects (and billing), so the reset retry is skipped — the same guard +// handleOpenAIUpstreamTransportError applies before failing over. +func openAIUpstreamRequestMayHaveReachedUpstreamViaPlugin(err error) bool { + var pluginErr *PluginTransportError + return errors.As(err, &pluginErr) && pluginErr != nil && pluginErr.RequestSent +} + +// openAIUpstreamResetRetryAllowed reports whether the attempt that just failed +// may be replayed once on the same account. The window is deliberately narrow: +// - the failure is a connection reset/EOF (see the classifier above); +// - the client is still connected, so the replay has a reader; +// - the request body can be re-created; +// - no byte reached the client for this attempt. Non-semantic keepalive +// comments are excluded, matching the existing first-output failover +// accounting: they carry no model output, so replaying cannot duplicate +// content the client already consumed. +func openAIUpstreamResetRetryAllowed( + c *gin.Context, + req *http.Request, + clientCtx context.Context, + outputSizeBefore int, + connectionReset bool, +) bool { + if !connectionReset { + return false + } + if c == nil || c.Writer == nil || req == nil || req.GetBody == nil { + // Without GetBody the consumed request body cannot be replayed; replaying + // would send an empty/partial payload and bill a second broken attempt. + return false + } + if clientCtx != nil && clientCtx.Err() != nil { + return false + } + if IsResponseCommitted(c) { + return false + } + return OpenAICompactKeepaliveAdjustedWrittenSize(c) == outputSizeBefore +} diff --git a/backend/internal/service/openai_upstream_connection_reset_retry_test.go b/backend/internal/service/openai_upstream_connection_reset_retry_test.go new file mode 100644 index 0000000000..c796a8ffda --- /dev/null +++ b/backend/internal/service/openai_upstream_connection_reset_retry_test.go @@ -0,0 +1,337 @@ +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "syscall" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Issue #8933: a CDN reset of one upstream HTTP/2 connection fails every stream +// multiplexed on it. When the reset lands after the connection was established +// but before any byte reaches the client, Forward must replay the request once on +// the same account instead of failing the account over. These tests pin the +// retry window: pre-output reset retried once, post-output reset not retried, +// timeout/cancel not retried, and a non-replayable body not retried. + +const openAIResetRetryCompletedStream = "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_reset_retry","status":"in_progress"}}` + "\n\n" + + "event: response.output_text.delta\n" + + `data: {"type":"response.output_text.delta","delta":"recovered","output_index":0}` + "\n\n" + + "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_reset_retry","status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"recovered"}]}],"usage":{"input_tokens":5,"output_tokens":2}}}` + "\n\n" + +// openAIResetRetryUpstream scripts one upstream outcome per attempt and records +// the request bodies so a replay can be compared with the original attempt. +type openAIResetRetryUpstream struct { + responses []*http.Response + errors []error + // clearGetBody simulates a one-shot request body: after the first send the + // request can no longer be recreated from GetBody. + clearGetBody bool + + requests []*http.Request + bodies [][]byte +} + +func (u *openAIResetRetryUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + attempt := len(u.requests) + u.requests = append(u.requests, req) + if req.Body != nil { + body, readErr := io.ReadAll(req.Body) + if readErr == nil { + u.bodies = append(u.bodies, append([]byte(nil), body...)) + _ = req.Body.Close() + req.Body = io.NopCloser(bytes.NewReader(body)) + } + } + if u.clearGetBody { + req.GetBody = nil + } + if attempt < len(u.errors) && u.errors[attempt] != nil { + return nil, u.errors[attempt] + } + if attempt < len(u.responses) { + return u.responses[attempt], nil + } + return nil, errors.New("unexpected upstream attempt") +} + +func (u *openAIResetRetryUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, accountConcurrency) +} + +func newOpenAIResetRetryForward(t *testing.T, upstream HTTPUpstream, ctx context.Context) (*gin.Context, *httptest.ResponseRecorder, []byte, *OpenAIGatewayService) { + t.Helper() + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-5.5","stream":true,"input":[{"type":"message","role":"user","content":"hi"}]}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + if ctx == nil { + ctx = context.Background() + } + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + return c, rec, body, &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} +} + +func newOpenAIResetRetryAccount() *Account { + return &Account{ + ID: 8933, + Name: "openai-oauth", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}, + Status: StatusActive, + Schedulable: true, + } +} + +func openAIResetRetryStreamResponse(requestID string, body io.ReadCloser) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "X-Request-Id": []string{requestID}}, + Body: body, + } +} + +// 首字节前连接被重置:同账号重放一次后成功,客户端拿到完整响应。 +func TestOpenAIForwardRetriesConnectionResetBeforeOutputOnSameAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIResetRetryUpstream{ + responses: []*http.Response{ + openAIResetRetryStreamResponse("rid-reset-before-output", &openAIStreamReadThenErrorCloser{ + reader: strings.NewReader(""), + err: syscall.ECONNRESET, + }), + openAIResetRetryStreamResponse("rid-retry-ok", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))), + }, + } + c, rec, body, svc := newOpenAIResetRetryForward(t, upstream, nil) + + result, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body) + + require.NoError(t, err) + require.NotNil(t, result) + require.Len(t, upstream.requests, 2, "reset before any client byte must be replayed exactly once") + require.Equal(t, upstream.requests[0].URL.String(), upstream.requests[1].URL.String(), + "the replay must stay on the same upstream endpoint/account") + require.Len(t, upstream.bodies, 2) + require.Equal(t, upstream.bodies[0], upstream.bodies[1], "the replay must resend the original request body") + require.Equal(t, 5, result.Usage.InputTokens) + require.Contains(t, rec.Body.String(), "response.completed") + require.NotContains(t, rec.Body.String(), "upstream_stream_read_error") +} + +// 响应头到达前 TCP 连接被重置(issue 中 146/147 的形态):同账号重放一次后成功。 +func TestOpenAIForwardRetriesTransportConnectionResetBeforeResponseHeaders(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIResetRetryUpstream{ + errors: []error{syscall.ECONNRESET, nil}, + responses: []*http.Response{ + nil, + openAIResetRetryStreamResponse("rid-retry-after-header-reset", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))), + }, + } + c, rec, body, svc := newOpenAIResetRetryForward(t, upstream, nil) + + result, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body) + + require.NoError(t, err) + require.NotNil(t, result) + require.Len(t, upstream.requests, 2, "a reset before response headers must be replayed exactly once") + require.Len(t, upstream.bodies, 2) + require.Equal(t, upstream.bodies[0], upstream.bodies[1], "the replay must resend the original request body") + require.Equal(t, 5, result.Usage.InputTokens) + require.Contains(t, rec.Body.String(), "response.completed") +} + +// 重放本身再次被重置:整个请求只多试一次,随后按原错误返回 failover。 +func TestOpenAIForwardRetriesConnectionResetOnlyOnce(t *testing.T) { + gin.SetMode(gin.TestMode) + newResetResponse := func(requestID string) *http.Response { + return openAIResetRetryStreamResponse(requestID, &openAIStreamReadThenErrorCloser{ + reader: strings.NewReader(""), + err: syscall.ECONNRESET, + }) + } + upstream := &openAIResetRetryUpstream{responses: []*http.Response{ + newResetResponse("rid-reset-first"), + newResetResponse("rid-reset-second"), + }} + c, _, body, svc := newOpenAIResetRetryForward(t, upstream, nil) + + _, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.Len(t, upstream.requests, 2, "a second reset must not start a third attempt") +} + +// 已经向客户端写出字节后再重置:SSE 无法续传,不得重放(回归)。 +func TestOpenAIForwardDoesNotRetryConnectionResetAfterClientOutput(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIResetRetryUpstream{ + responses: []*http.Response{ + openAIResetRetryStreamResponse("rid-reset-after-output", &openAIStreamReadThenErrorCloser{ + reader: strings.NewReader("event: response.output_text.delta\n" + + `data: {"type":"response.output_text.delta","delta":"partial","output_index":0}` + "\n\n"), + err: syscall.ECONNRESET, + }), + }, + } + c, rec, body, svc := newOpenAIResetRetryForward(t, upstream, nil) + + _, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body) + + require.Error(t, err) + require.Contains(t, err.Error(), "stream read error") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "a post-output reset cannot be replayed") + require.Len(t, upstream.requests, 1, "no replay once bytes reached the client") + require.Contains(t, rec.Body.String(), "partial") +} + +// 超时 / 客户端取消不是共享连接被重置,不得重放。 +func TestOpenAIForwardDoesNotRetryConnectionResetOnTimeoutOrCancel(t *testing.T) { + gin.SetMode(gin.TestMode) + timeoutErr := &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: &net.OpError{ + Op: "read", Net: "tcp", Err: openAIResetRetryTimeoutError{}, + }} + for _, tc := range []struct { + name string + err error + ctx context.Context + }{ + {name: "deadline_exceeded", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: context.DeadlineExceeded}}, + {name: "network_timeout", err: timeoutErr}, + {name: "client_canceled", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: syscall.ECONNRESET}, ctx: canceledOpenAIResetRetryContext()}, + } { + t.Run(tc.name, func(t *testing.T) { + upstream := &openAIResetRetryUpstream{ + errors: []error{tc.err}, + responses: []*http.Response{ + openAIResetRetryStreamResponse("rid-unused", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))), + }, + } + c, _, body, svc := newOpenAIResetRetryForward(t, upstream, tc.ctx) + + _, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body) + + require.Error(t, err) + require.Len(t, upstream.requests, 1, "timeout/cancel must not be replayed") + }) + } +} + +// body 不可重放(GetBody 为空)时放弃重放,返回原错误。 +func TestOpenAIForwardDoesNotRetryConnectionResetWhenBodyIsNotReplayable(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIResetRetryUpstream{ + clearGetBody: true, + errors: []error{syscall.ECONNRESET}, + responses: []*http.Response{ + openAIResetRetryStreamResponse("rid-unused", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))), + }, + } + c, _, body, svc := newOpenAIResetRetryForward(t, upstream, nil) + + _, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.Len(t, upstream.requests, 1, "a body that cannot be recreated must not be replayed") +} + +func TestOpenAIUpstreamConnectionResetClassifier(t *testing.T) { + for _, tc := range []struct { + name string + err error + want bool + }{ + {name: "nil", err: nil, want: false}, + {name: "econnreset", err: syscall.ECONNRESET, want: true}, + {name: "wrapped_econnreset", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: &net.OpError{ + Op: "read", Net: "tcp", Err: syscall.ECONNRESET, + }}, want: true}, + {name: "unexpected_eof", err: io.ErrUnexpectedEOF, want: true}, + {name: "http2_connection_lost", err: errors.New("http2: client connection lost"), want: true}, + {name: "http2_goaway", err: errors.New("http2: server sent GOAWAY and closed the connection; LastStreamID=3"), want: true}, + {name: "http2_stream_error", err: errors.New("stream error: stream ID 5; INTERNAL_ERROR"), want: true}, + {name: "context_canceled", err: context.Canceled, want: false}, + {name: "deadline_exceeded", err: context.DeadlineExceeded, want: false}, + {name: "timeout_text", err: errors.New("http2: timeout awaiting response headers"), want: false}, + {name: "connection_refused", err: errors.New("dial tcp 192.0.2.1:443: connect: connection refused"), want: false}, + {name: "dial_reset", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: &net.OpError{ + Op: "dial", Net: "tcp", Err: syscall.ECONNRESET, + }}, want: false}, + {name: "dns", err: errors.New(`lookup upstream.example: no such host`), want: false}, + {name: "unrelated", err: errors.New("boom"), want: false}, + } { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, isOpenAIUpstreamConnectionResetError(tc.err)) + }) + } +} + +type openAIResetRetryTimeoutError struct{} + +func (openAIResetRetryTimeoutError) Error() string { return "i/o timeout" } +func (openAIResetRetryTimeoutError) Timeout() bool { return true } +func (openAIResetRetryTimeoutError) Temporary() bool { return true } + +func canceledOpenAIResetRetryContext() context.Context { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + return ctx +} + +// 流式读错误在首字节前才标记为可由 Forward 重放;其他读错误保持原有 failover 语义。 +func TestOpenAIStreamReadErrorMarksConnectionResetOnlyBeforeOutput(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + payload string + err error + wantReset bool + }{ + {name: "reset_before_output", payload: "", err: syscall.ECONNRESET, wantReset: true}, + {name: "unexpected_eof_before_output", payload: "", err: io.ErrUnexpectedEOF, wantReset: true}, + {name: "other_read_error", payload: "", err: errors.New("boom"), wantReset: false}, + } { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}} + resp := openAIResetRetryStreamResponse("rid-stream-reset", &openAIStreamReadThenErrorCloser{ + reader: strings.NewReader(tc.payload), + err: tc.err, + }) + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, newOpenAIResetRetryAccount(), time.Now(), "gpt-5.5", "gpt-5.5") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, tc.wantReset, failoverErr.ConnectionResetBeforeOutput) + require.False(t, c.Writer.Written(), "no client-visible byte before the first output") + }) + } +}