From 189b336f47133dabe68ad0fa5d2c35a128210c73 Mon Sep 17 00:00:00 2001 From: WGeorgezzzz <257936154+WGeorgezzzz@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:45:33 +0800 Subject: [PATCH] fix(openai): enforce stream idle deadlines and pre-output failover --- .../openai_gateway_response_handling.go | 22 +++-- .../openai_stream_idle_timeout_test.go | 84 +++++++++++++++++++ 2 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 backend/internal/service/openai_stream_idle_timeout_test.go diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index a2b0fae6a2..3d3e868400 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -186,14 +186,14 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. streamInterval = resolveGrokStreamIdleTimeout(cfgSec) } // 仅监控上游数据间隔超时,不被下游写入阻塞影响 - var intervalTicker *time.Ticker + var intervalTimer *time.Timer if streamInterval > 0 { - intervalTicker = time.NewTicker(streamInterval) - defer intervalTicker.Stop() + intervalTimer = time.NewTimer(streamInterval) + defer intervalTimer.Stop() } var intervalCh <-chan time.Time - if intervalTicker != nil { - intervalCh = intervalTicker.C + if intervalTimer != nil { + intervalCh = intervalTimer.C } keepaliveInterval := time.Duration(0) @@ -937,7 +937,9 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. return resultWithUsage(), fmt.Errorf("upstream response failed: %s", failedMessage) } lastRead := time.Unix(0, atomic.LoadInt64(&lastReadAt)) - if time.Since(lastRead) < streamInterval { + if remaining := streamInterval - time.Since(lastRead); remaining > 0 { + // Re-arm for the actual last-read deadline. + intervalTimer.Reset(remaining) continue } if codexFailureTerminal && sawBareError && !sawResponseFailed { @@ -952,6 +954,14 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. if s.rateLimitService != nil { s.rateLimitService.HandleStreamTimeout(ctx, account, originalModel) } + if account != nil && account.Platform == PlatformOpenAI && + !openAIStreamClientOutputStarted(c, clientOutputStarted) && !eventShouldFlush { + _ = resp.Body.Close() + return resultWithUsage(), s.newOpenAIStreamFailoverErrorWithModel( + c, account, false, upstreamRequestID, nil, + "OpenAI upstream stream idle timeout before model output", mappedModel, resp.Header, + ) + } // Grok: short cool + account failover when no client-visible bytes // were committed yet (pre-commit). After output started we keep the // legacy stream_timeout path so partial SSE is not dual-written. diff --git a/backend/internal/service/openai_stream_idle_timeout_test.go b/backend/internal/service/openai_stream_idle_timeout_test.go new file mode 100644 index 0000000000..6338c25041 --- /dev/null +++ b/backend/internal/service/openai_stream_idle_timeout_test.go @@ -0,0 +1,84 @@ +package service + +import ( + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestRelayStallsIdleDeadlineTracksLastRead(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, StreamDataIntervalTimeout: 1, + }}} + pr, pw := io.Pipe() + defer func() { _ = pr.Close() }() + defer func() { _ = pw.Close() }() + go func() { + time.Sleep(250 * time.Millisecond) + _, _ = io.WriteString(pw, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"r\"}}\n\n") + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + start := time.Now() + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, account, start, "model", "model") + elapsed := time.Since(start) + t.Logf("idle timeout after %s (last upstream read at approximately 250ms)", elapsed) + require.Error(t, err) + require.GreaterOrEqual(t, elapsed, 1200*time.Millisecond, "do not shorten the configured idle interval") + require.Less(t, elapsed, 1800*time.Millisecond, "do not wait for the next full polling interval") + var failover *UpstreamFailoverError + require.True(t, errors.As(err, &failover), "an idle attempt with no model output should remain failover-safe") + require.Empty(t, rec.Body.String()) +} + +func TestRelayStallsIdleFailoverBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, output := range []bool{false, true} { + name := "before_output" + if output { + name = "after_output" + } + t.Run(name, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, StreamDataIntervalTimeout: 1, + }}} + pr, pw := io.Pipe() + defer func() { _ = pr.Close() }() + defer func() { _ = pw.Close() }() + go func() { + frame := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"r\"}}\n\n" + if output { + frame += "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hello\"}\n\n" + } + _, _ = io.WriteString(pw, frame) + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + require.Error(t, err) + var failover *UpstreamFailoverError + if output { + require.False(t, errors.As(err, &failover), "partial output must not be replayed") + require.Contains(t, rec.Body.String(), "hello") + require.Contains(t, rec.Body.String(), "stream_timeout") + } else { + require.ErrorAs(t, err, &failover) + require.Empty(t, rec.Body.String()) + } + }) + } +}