From c1c9d195b3a4c7f4af5673d032c12083d4ae8cb1 Mon Sep 17 00:00:00 2001 From: qsy4 <28869029+qsy4@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:24:36 -0800 Subject: [PATCH] fix(openai): forward upstream keepalive events before first output Problem: on native Responses streams the gateway stages every event of an attempt until the first semantic output, so it can still fail over to another account. Upstream keepalive events are staged with the rest. When the upstream is silent for a long time (long high-effort reasoning), the client only receives ":" comment heartbeats. Codex resets its stream idle timer on parsed SSE events only, so it gives up after its 300 second idle timeout ("idle timeout waiting for SSE") while the upstream is still working, and the gateway keeps reading a stream nobody will receive. Fix: while the first-output stage is open, write upstream keepalive events (both the "event: keepalive" + data form and the data-only form) straight to the client, the same way the comment keepalive bypasses the stage: only the stable SSE headers are committed, the attempt's lifecycle events and account headers stay private, and the bytes are recorded with recordOpenAIStreamKeepaliveBytes so they still do not count as client output and pre-output failover keeps working. The WebSocket to HTTP bridge already forwards keepalive before first output this way. Events after output started are unchanged. Keepalive events are not output, so they do not stop the first-output timer: with gateway.openai_first_output_timeout_seconds set, a stalled attempt still fails over on time while the client stays connected. Test: TestOpenAINativeStreamForwardsUpstreamKeepaliveBeforeFirstOutput covers both frame shapes. TestOpenAINativeStreamKeepaliveThenFailoverContinuesWithNextAccount checks that failover after a forwarded keepalive streams the next account from its start. TestOpenAINativeStreamKeepaliveDoesNotResetFirstOutputTimeout checks that paced keepalives do not postpone the timeout. TestOpenAINativeStreamKeepaliveAfterOutputStaysInOrder guards the post-output path. TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver, TestOpenAIStreamKeepaliveOnlyFailureDoesNotRecordFirstToken and TestOpenAINativeMetadataAndKeepaliveDoNotDisarmFirstOutputTimeout asserted that the client receives nothing before first output on the native path. Their native cases now assert that only the upstream keepalive frames reach the client and that those bytes still do not count as output; the passthrough cases are unchanged. --- .../service/openai_capacity_shed_test.go | 13 ++ .../openai_gateway_response_handling.go | 41 ++++ ...i_gateway_stream_keepalive_forward_test.go | 215 ++++++++++++++++++ .../service/openai_visible_ttft_test.go | 4 +- 4 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/openai_gateway_stream_keepalive_forward_test.go diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index 6737e42cbd..ae060c02dd 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -241,6 +241,13 @@ func TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver(t *testing.T) { require.True(t, failoverErr.RequestScopedTransient) require.Equal(t, http.StatusServiceUnavailable, failoverErr.ClientStatusCode) require.Contains(t, failoverErr.ClientMessage, "servers are currently overloaded") + if tt.name == "native" { + // Only the upstream keepalive events reach the client before first output. + require.Equal(t, "event: keepalive\ndata: {\"type\":\"keepalive\"}\n\ndata: {\"type\":\"keepalive\"}\n\n", rec.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) + require.Empty(t, rec.Header().Get("X-Request-Id")) + return + } require.False(t, c.Writer.Written()) require.Empty(t, rec.Body.String()) }) @@ -354,6 +361,12 @@ func TestOpenAIStreamKeepaliveOnlyFailureDoesNotRecordFirstToken(t *testing.T) { require.ErrorAs(t, err, &failoverErr) require.True(t, failoverErr.RetryableOnSameAccount) require.True(t, failoverErr.RequestScopedTransient) + if !passthrough { + // Only the upstream keepalive event reaches the client before first output. + require.Equal(t, "data: {\"type\":\"keepalive\"}\n\n", rec.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) + return + } require.Empty(t, rec.Body.String()) }) } diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index ae528e4fea..3d1d67af84 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -484,6 +484,25 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. sendErrorEvent(code, message) return resultWithUsage(), fmt.Errorf("stream read error: %w", scanErr), true } + // Upstream keepalive events bypass the first-output stage the same way the + // comment keepalive does: Codex resets its stream idle timer only on parsed + // SSE events, while the attempt's lifecycle events and account headers stay + // private until semantic output. The bytes do not count as client output. + keepaliveEventDirect := false + forwardsKeepaliveDirect := func(eventType string) bool { + return eventType == "keepalive" && stageFirstOutput && !firstOutputStage.closed && !failureDelivered && !suppressCurrentEvent + } + writeKeepaliveDirect := func(value string) { + if clientDisconnected { + return + } + n, err := w.Write([]byte(value)) + recordOpenAIStreamKeepaliveBytes(c, n) + if err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") + } + } processSSELine := func(line string, queueDrained bool) { if streamEarlyErr != nil { return @@ -492,11 +511,23 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. pendingSSEEventType = eventType eventType = strings.TrimSpace(eventType) suppressCurrentEvent = codexFailureTerminal && (eventType == "error" || (sawBareError && !sawResponseFailed && eventType != "response.failed")) + if forwardsKeepaliveDirect(eventType) { + keepaliveEventDirect = true + eventInProgress = true + writeKeepaliveDirect(line + "\n") + return + } } // Extract data from SSE line (supports both "data: " and "data:" formats) if data, ok := extractOpenAISSEDataLine(line); ok { dataBytes := []byte(data) eventType := effectiveOpenAISSEEventType(dataBytes, pendingSSEEventType) + if keepaliveEventDirect || forwardsKeepaliveDirect(eventType) { + keepaliveEventDirect = true + eventInProgress = true + writeKeepaliveDirect(line + "\n") + return + } if codexFailureTerminal && sawBareError && !sawResponseFailed && (eventType == "response.completed" || eventType == "response.done") { // A later successful terminal is authoritative over a pending bare @@ -748,6 +779,16 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. // A blank line dispatches a guarded event from the attempt-local stage. if stageFirstOutput && line == "" { pendingSSEEventType = "" + if keepaliveEventDirect { + keepaliveEventDirect = false + eventInProgress = false + writeKeepaliveDirect("\n") + if !clientDisconnected { + flusher.Flush() + lastDownstreamWriteAt = time.Now() + } + return + } if suppressCurrentEvent { suppressCurrentEvent = false terminalFailurePending = false diff --git a/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go b/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go new file mode 100644 index 0000000000..d83e2a3d41 --- /dev/null +++ b/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go @@ -0,0 +1,215 @@ +package service + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// keepaliveForwardBody holds the upstream stream open until the gateway closes it. +type keepaliveForwardBody struct { + io.ReadCloser + closed chan struct{} + once sync.Once +} + +func (b *keepaliveForwardBody) Close() error { + b.once.Do(func() { close(b.closed) }) + return b.ReadCloser.Close() +} + +// stalledKeepaliveResponse returns an upstream response that sends the preamble and the given +// keepalive frames, then produces no semantic output until it is closed. +func stalledKeepaliveResponse(frames ...string) *http.Response { + pr, pw := io.Pipe() + body := &keepaliveForwardBody{ReadCloser: pr, closed: make(chan struct{})} + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_stalled\"}}\n\n")) + _, _ = pw.Write([]byte("data: {\"type\":\"response.in_progress\",\"response\":{\"id\":\"resp_stalled\"}}\n\n")) + for _, frame := range frames { + _, _ = pw.Write([]byte(frame)) + } + select { + case <-body.closed: + case <-time.After(5 * time.Second): + } + }() + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{"text/event-stream"}, + "X-Request-Id": []string{"request-stalled"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: body, + } +} + +func newKeepaliveForwardService(firstOutputTimeoutSeconds int) *OpenAIGatewayService { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: firstOutputTimeoutSeconds, + MaxLineSize: defaultMaxLineSize, + }} + return &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} +} + +func newKeepaliveForwardContext() (*gin.Context, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + return c, rec +} + +const ( + upstreamKeepaliveData = `data: {"type":"keepalive","sequence_number":3}` + upstreamKeepaliveEvent = "event: keepalive\n" + upstreamKeepaliveData + "\n\n" +) + +// Codex resets its stream idle timer only on parsed SSE events, so the upstream keepalive event +// must reach the client before the first semantic output, while the attempt's preamble and +// account headers stay private and the bytes still do not count as client output. +func TestOpenAINativeStreamForwardsUpstreamKeepaliveBeforeFirstOutput(t *testing.T) { + for _, tc := range []struct { + name string + frame string + }{ + {"event_and_data", upstreamKeepaliveEvent}, + {"data_only", upstreamKeepaliveData + "\n\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + _, err := svc.handleStreamingResponse(c.Request.Context(), stalledKeepaliveResponse(tc.frame), c, + &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr, "no semantic output: the first-output timeout must fail over") + require.Equal(t, tc.frame, rec.Body.String(), "only the upstream keepalive event reaches the client, verbatim") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c), "keepalive bytes are not client output") + require.Empty(t, rec.Result().Header.Values("X-Request-Id"), "account headers stay private before output") + require.Empty(t, rec.Result().Header.Values("X-Ratelimit-Remaining-Requests")) + }) + } +} + +// After a pre-output failover the next account's stream continues the same response: the client +// sees the first account's keepalive, then the second account's complete stream from its start. +func TestOpenAINativeStreamKeepaliveThenFailoverContinuesWithNextAccount(t *testing.T) { + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + _, firstErr := svc.handleStreamingResponse(c.Request.Context(), stalledKeepaliveResponse(upstreamKeepaliveEvent), c, + &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, firstErr, &failoverErr) + + secondResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "X-Request-Id": []string{"request-second"}}, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_second"}}`, + "", + `data: {"type":"response.output_text.delta","delta":"hello"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_second","usage":{"input_tokens":1,"output_tokens":1}}}`, + "", + }, "\n"))), + } + result, secondErr := svc.handleStreamingResponse(c.Request.Context(), secondResp, c, + &Account{ID: 2, Platform: PlatformOpenAI}, time.Now(), "model", "model") + require.NoError(t, secondErr) + require.NotNil(t, result) + + body := rec.Body.String() + require.True(t, strings.HasPrefix(body, upstreamKeepaliveEvent), "first account's keepalive comes first, got %q", body) + require.NotContains(t, body, "resp_stalled", "the failed attempt's preamble never reaches the client") + created := strings.Index(body, `"id":"resp_second"`) + require.Greater(t, created, len(upstreamKeepaliveEvent)-1) + require.Less(t, created, strings.Index(body, `"delta":"hello"`)) + require.Empty(t, rec.Result().Header.Values("X-Request-Id"), "headers were committed by the keepalive, not the second account") +} + +// Keepalive events after output started keep their place in the stream: not dropped, not repeated. +func TestOpenAINativeStreamKeepaliveAfterOutputStaysInOrder(t *testing.T) { + svc := newKeepaliveForwardService(0) + c, rec := newKeepaliveForwardContext() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_order"}}`, + "", + `data: {"type":"response.output_text.delta","delta":"a"}`, + "", + "event: keepalive", + upstreamKeepaliveData, + "", + `data: {"type":"response.output_text.delta","delta":"b"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_order","usage":{"input_tokens":1,"output_tokens":2}}}`, + "", + }, "\n"))), + } + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + require.NoError(t, err) + + body := rec.Body.String() + require.Equal(t, 1, strings.Count(body, `"type":"keepalive"`)) + a, ka, b := strings.Index(body, `"delta":"a"`), strings.Index(body, upstreamKeepaliveEvent), strings.Index(body, `"delta":"b"`) + require.True(t, a < ka && ka < b, "keepalive must stay between the deltas, got %q", body) +} + +// Forwarded keepalive events are not output: they must not postpone the first-output timeout, +// so an attempt whose upstream only keeps the stream alive still fails over on time. +func TestOpenAINativeStreamKeepaliveDoesNotResetFirstOutputTimeout(t *testing.T) { + pr, pw := io.Pipe() + body := &keepaliveForwardBody{ReadCloser: pr, closed: make(chan struct{})} + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_paced\"}}\n\n")) + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + deadline := time.After(4 * time.Second) + for { + select { + case <-body.closed: + return + case <-deadline: + return + case <-ticker.C: + if _, err := pw.Write([]byte(upstreamKeepaliveEvent)); err != nil { + return + } + } + } + }() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: body, + } + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + started := time.Now() + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, started, "model", "model") + elapsed := time.Since(started) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Less(t, elapsed, 2500*time.Millisecond, "keepalive events must not reset the first-output timer") + require.GreaterOrEqual(t, strings.Count(rec.Body.String(), upstreamKeepaliveEvent), 2, "keepalives reached the client before the timeout") + require.NotContains(t, rec.Body.String(), "resp_paced") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) +} diff --git a/backend/internal/service/openai_visible_ttft_test.go b/backend/internal/service/openai_visible_ttft_test.go index 24a60e21e2..87497f39f0 100644 --- a/backend/internal/service/openai_visible_ttft_test.go +++ b/backend/internal/service/openai_visible_ttft_test.go @@ -98,7 +98,9 @@ func TestOpenAINativeMetadataAndKeepaliveDoNotDisarmFirstOutputTimeout(t *testin var failoverErr *UpstreamFailoverError require.ErrorAs(t, err, &failoverErr) require.True(t, failoverErr.SafeToFailoverAfterWrite) - require.Empty(t, recorder.Body.String()) + // Only the upstream keepalive event reaches the client; it is not output. + require.Equal(t, "data: {\"type\":\"keepalive\"}\n\n", recorder.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) select { case <-writerDone: case <-time.After(time.Second):