fix(openai): apply account side effects to stream errors after output on compat paths

Problem: on /v1/chat/completions and /v1/messages the upstream responses
stream is converted as it arrives, so client output starts with the first
event (a role chunk or message_start written for response.created). A
terminal error event that arrives after that can no longer fail over, and
the branch that handles it only records the error. Unlike /v1/responses
and the WebSocket forwarder, which call
handleOpenAIStreamTerminalAccountSideEffects in the same situation, the
account health is never updated: a rate limited, quota exhausted or
deauthorized account stays schedulable and every new request routed to it
fails the same way.

Fix: call handleOpenAIStreamTerminalAccountSideEffects in the
non-failover branch of both compat stream handlers, before the error is
recorded, with the same arguments the failover constructor uses. The
failover branch is unchanged; it already applies the side effects inside
newOpenAIStreamFailoverErrorWithModel, so each upstream attempt is still
counted once.

Test: TestForwardAsChatCompletions_StreamErrorAfterOutputAppliesAccountSideEffects
and TestForwardAsAnthropic_StreamErrorAfterOutputAppliesAccountSideEffects
check that an auth error after output marks the account exactly once. The
two StreamErrorBeforeOutputCountsOnce tests check that the failover path
still marks the account exactly once.
This commit is contained in:
qsy4 committed 2026-11-14 07:41:11 -08:00
1 parent 530c5e3a4f
commit 975b2807d1
3 files changed
+147

No files matched your search

@@ -974,6 +974,7 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse(
streamFailoverErr = s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payloadBytes, message, upstreamModel, resp.Header)
return true
}
s.handleOpenAIStreamTerminalAccountSideEffects(c, account, payloadBytes, message, resp.Header, upstreamModel)
message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payloadBytes, message)
defaultStatus, defaultErrType, defaultMsg := http.StatusBadGateway, "upstream_error", message
// 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致),
@@ -0,0 +1,145 @@
package service
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// compatStreamSideEffectsRepo records the account-health writes made by the rate limit service.
type compatStreamSideEffectsRepo struct {
stubOpenAIAccountRepo
rateLimitCalls []time.Time
errorCalls []string
}
func (r *compatStreamSideEffectsRepo) SetRateLimited(_ context.Context, _ int64, resetAt time.Time) error {
r.rateLimitCalls = append(r.rateLimitCalls, resetAt)
return nil
}
func (r *compatStreamSideEffectsRepo) SetError(_ context.Context, _ int64, msg string) error {
r.errorCalls = append(r.errorCalls, msg)
return nil
}
func compatStreamSideEffectsAccount() Account {
return Account{
ID: 601,
Name: "openai-apikey-compat-stream",
Platform: PlatformOpenAI,
Type: AccountTypeAPIKey,
Status: StatusActive,
Schedulable: true,
Concurrency: 1,
Credentials: map[string]any{"api_key": "sk-test"},
}
}
// compatStreamSideEffectsSSE builds an upstream responses stream that fails with errorEvent.
// With outputFirst the error follows response.created and a text delta, so client output has
// started (in practice response.created alone already starts it on both compat paths); without,
// the error is the first event and the request can still fail over.
func compatStreamSideEffectsSSE(outputFirst bool, errorEvent string) string {
var lines []string
if outputFirst {
lines = append(lines,
`data: {"type":"response.created","response":{"id":"resp_side","model":"gpt-5.5","status":"in_progress","output":[]}}`,
"",
`data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"partial"}`,
"",
)
}
lines = append(lines, `event: error`, `data: `+errorEvent, "")
return strings.Join(lines, "\n")
}
const compatStreamAuthErrorEvent = `{"type":"error","status":401,"error":{"code":"invalid_api_key","type":"invalid_request_error","message":"Incorrect API key provided"}}`
func newCompatStreamSideEffectsService(sse string) (*OpenAIGatewayService, *compatStreamSideEffectsRepo, *Account) {
account := compatStreamSideEffectsAccount()
repo := &compatStreamSideEffectsRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}}
svc := &OpenAIGatewayService{
accountRepo: repo,
rateLimitService: &RateLimitService{accountRepo: repo},
httpUpstream: &httpUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_side"}},
Body: io.NopCloser(strings.NewReader(sse)),
}},
}
return svc, repo, &account
}
func newCompatStreamContext(path string, body []byte) (*gin.Context, *httptest.ResponseRecorder) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
return c, rec
}
// A terminal stream error that arrives after client output started can no longer fail over, but the
// account health still has to be updated — otherwise the account stays schedulable and every new
// request routed to it fails the same way.
func TestForwardAsChatCompletions_StreamErrorAfterOutputAppliesAccountSideEffects(t *testing.T) {
svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(true, compatStreamAuthErrorEvent))
body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"stream":true}`)
c, rec := newCompatStreamContext("/v1/chat/completions", body)
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5")
require.Error(t, err)
var failoverErr *UpstreamFailoverError
require.False(t, errors.As(err, &failoverErr), "output already started: must not fail over")
require.Contains(t, rec.Body.String(), "partial", "client output must have started before the error")
require.Len(t, repo.errorCalls, 1, "auth failure after output must mark the account exactly once")
require.Empty(t, repo.rateLimitCalls)
}
func TestForwardAsAnthropic_StreamErrorAfterOutputAppliesAccountSideEffects(t *testing.T) {
svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(true, compatStreamAuthErrorEvent))
body := []byte(`{"model":"gpt-5.5","max_tokens":1024,"messages":[{"role":"user","content":"hi"}],"stream":true}`)
c, rec := newCompatStreamContext("/v1/messages", body)
_, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5")
require.Error(t, err)
var failoverErr *UpstreamFailoverError
require.False(t, errors.As(err, &failoverErr), "output already started: must not fail over")
require.Contains(t, rec.Body.String(), "partial", "client output must have started before the error")
require.Len(t, repo.errorCalls, 1, "auth failure after output must mark the account exactly once")
require.Empty(t, repo.rateLimitCalls)
}
// Before client output the error fails over; the failover constructor already applies the side
// effects, so the account is marked once — not once per path.
func TestForwardAsChatCompletions_StreamErrorBeforeOutputCountsOnce(t *testing.T) {
svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(false, compatStreamAuthErrorEvent))
body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"stream":true}`)
c, _ := newCompatStreamContext("/v1/chat/completions", body)
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5")
var failoverErr *UpstreamFailoverError
require.True(t, errors.As(err, &failoverErr), "no output yet: must fail over, got %v", err)
require.Len(t, repo.errorCalls, 1, "failover path must not double count")
}
func TestForwardAsAnthropic_StreamErrorBeforeOutputCountsOnce(t *testing.T) {
svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(false, compatStreamAuthErrorEvent))
body := []byte(`{"model":"gpt-5.5","max_tokens":1024,"messages":[{"role":"user","content":"hi"}],"stream":true}`)
c, _ := newCompatStreamContext("/v1/messages", body)
_, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5")
var failoverErr *UpstreamFailoverError
require.True(t, errors.As(err, &failoverErr), "no output yet: must fail over, got %v", err)
require.Len(t, repo.errorCalls, 1, "failover path must not double count")
}
@@ -1154,6 +1154,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse(
streamFailoverErr = s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payloadBytes, message, upstreamModel, resp.Header)
return true
}
s.handleOpenAIStreamTerminalAccountSideEffects(c, account, payloadBytes, message, resp.Header, upstreamModel)
message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payloadBytes, message)
errStatus, errType, errMsg := http.StatusBadGateway, "api_error", message
// 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致),