mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(openai): skip same-account overload retries when Retry-After exceeds budget
When an OpenAI upstream sheds capacity (`server_is_overloaded` / `slow_down`) and advertises an explicit `Retry-After` longer than the per-retry delay cap (8s, e.g. 315-369s in #9183), replaying a single-credential account every 8s cannot satisfy the upstream window and delays switching to healthy accounts. Switch non-pool accounts immediately on long capacity-shed `Retry-After` hints while keeping short/unspecified blips and pool-mode relays retryable, preserve request-scoped transient semantics (no persistent account cooldown), and log `upstream_retry_after` on retry and switch events. Fixes #9183 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
f7ec8b3cee
commit
d07f63ddf8
9 files changed
+283
-87
No files matched your search
@@ -55,6 +55,13 @@ const (
|
||||
// 语义上等同于「无可用账号」:候选账号都不满足分组的利润约束。
|
||||
const profitVetoExhaustedMessage = "No available accounts: all candidates rejected by group profit control"
|
||||
|
||||
func appendUpstreamRetryAfterField(fields []zap.Field, failoverErr *service.UpstreamFailoverError) []zap.Field {
|
||||
if failoverErr != nil && failoverErr.UpstreamRetryAfter > 0 {
|
||||
return append(fields, zap.Duration("upstream_retry_after", failoverErr.UpstreamRetryAfter))
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryCount int) time.Duration {
|
||||
if failoverErr == nil {
|
||||
return sameAccountRetryDelay
|
||||
@@ -220,13 +227,14 @@ func (s *FailoverState) HandleFailoverError(
|
||||
if sameAccountRetry {
|
||||
s.SameAccountRetryCount[accountID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, s.SameAccountRetryCount[accountID])
|
||||
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("same_account_retry_count", s.SameAccountRetryCount[accountID]),
|
||||
zap.Int("same_account_retry_max", retryLimit),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry", retryFields...)
|
||||
if !sleepWithContext(ctx, retryDelay) {
|
||||
return FailoverCanceled
|
||||
}
|
||||
@@ -248,12 +256,13 @@ func (s *FailoverState) HandleFailoverError(
|
||||
|
||||
// 递增切换计数
|
||||
s.SwitchCount++
|
||||
logger.FromContext(ctx).Warn("gateway.failover_switch_account",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", s.SwitchCount),
|
||||
zap.Int("max_switches", s.MaxSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
logger.FromContext(ctx).Warn("gateway.failover_switch_account", switchFields...)
|
||||
|
||||
// Antigravity 平台换号线性递增延时
|
||||
if platform == service.PlatformAntigravity {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func capacityShedSSEOverloadResponse(retryAfterSec string) *http.Response {
|
||||
stream := fmt.Sprintf(
|
||||
"event: response.created\n"+
|
||||
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_shed\"}}\n\n"+
|
||||
"event: error\n"+
|
||||
"data: {\"type\":\"error\",\"error\":{\"type\":\"service_unavailable_error\",\"code\":\"server_is_overloaded\",\"message\":\"Our servers are currently overloaded. Please try again later.\",\"headers\":{\"retry-after\":%q}}}\n\n",
|
||||
retryAfterSec,
|
||||
)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(bytes.NewBufferString(stream)),
|
||||
}
|
||||
}
|
||||
|
||||
func capacityShedHTTPOverloadResponse(retryAfterMs string) *http.Response {
|
||||
h := http.Header{"Content-Type": []string{"application/json"}}
|
||||
if retryAfterMs != "" {
|
||||
h.Set("Retry-After-Ms", retryAfterMs)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusServiceUnavailable,
|
||||
Header: h,
|
||||
Body: io.NopCloser(bytes.NewBufferString(
|
||||
`{"error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_LongOverloadRetryAfterSwitchesImmediately(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(capacityShedSSEOverloadResponse("315"), astra200())
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 2}, accountIDs)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "completed", gjson.GetBytes(rec.Body.Bytes(), "status").String())
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_ShortOverloadRetryAfterRetriesSameAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(capacityShedHTTPOverloadResponse("10"), astra200())
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 1}, accountIDs)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_AllAccountsLongOverloadFailsFast503(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(
|
||||
capacityShedSSEOverloadResponse("315"),
|
||||
capacityShedSSEOverloadResponse("335"),
|
||||
)
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 2}, accountIDs)
|
||||
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
|
||||
require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "servers are currently overloaded")
|
||||
}
|
||||
@@ -359,13 +359,14 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -386,12 +387,13 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_chat_completions.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_chat_completions.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, nil), false, nil, err)
|
||||
|
||||
@@ -981,13 +981,14 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -1024,6 +1025,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
} else if account.ProxyID != nil {
|
||||
failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID))
|
||||
}
|
||||
failoverSwitchFields = appendUpstreamRetryAfterField(failoverSwitchFields, failoverErr)
|
||||
reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...)
|
||||
continue
|
||||
}
|
||||
@@ -1561,13 +1563,14 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_messages.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_messages.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -1588,12 +1591,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_messages.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_messages.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
if result != nil && result.ClientDisconnect {
|
||||
|
||||
@@ -333,13 +333,14 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai.images.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.images.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-requestCtx.Done():
|
||||
return
|
||||
@@ -360,12 +361,13 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai.images.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.images.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), false, nil, err)
|
||||
|
||||
@@ -794,6 +794,7 @@ type UpstreamFailoverError struct {
|
||||
ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true
|
||||
RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换
|
||||
SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值
|
||||
UpstreamRetryAfter time.Duration // 上游原始 Retry-After 建议时长(未截断),用于决策与可观测日志
|
||||
SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制
|
||||
SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用
|
||||
RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁
|
||||
|
||||
@@ -112,16 +112,78 @@ func TestOpenAIHTTPCapacityShedIsRequestScopedForOAuthAccounts(t *testing.T) {
|
||||
|
||||
func TestOpenAICapacityShedHonorsRetryAfter(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
headers http.Header
|
||||
body string
|
||||
want time.Duration
|
||||
name string
|
||||
headers http.Header
|
||||
body string
|
||||
callerSameAccount bool
|
||||
wantDelay time.Duration
|
||||
wantUpstreamHint time.Duration
|
||||
wantSameAccountTry bool
|
||||
}{
|
||||
{name: "http seconds", headers: http.Header{"Retry-After": []string{"6"}}, want: 6 * time.Second},
|
||||
{name: "http milliseconds", headers: http.Header{"Retry-After-Ms": []string{"6000"}}, want: 6 * time.Second},
|
||||
{name: "body seconds", body: `{"error":{"headers":{"retry-after":"7"},"message":"Our servers are currently overloaded. Please try again later."}}`, want: 7 * time.Second},
|
||||
{name: "body milliseconds", body: `{"response":{"error":{"headers":{"retry-after-ms":"7000"},"message":"Our servers are currently overloaded. Please try again later."}}}`, want: 7 * time.Second},
|
||||
{name: "bounded", headers: http.Header{"Retry-After": []string{"60"}}, want: openAIRequestScopedRetryMaxDelay},
|
||||
{
|
||||
name: "missing retry-after keeps same-account retry",
|
||||
body: `{"error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`,
|
||||
wantDelay: 0,
|
||||
wantUpstreamHint: 0,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "http seconds within budget",
|
||||
headers: http.Header{"Retry-After": []string{"6"}},
|
||||
wantDelay: 6 * time.Second,
|
||||
wantUpstreamHint: 6 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "http milliseconds within budget",
|
||||
headers: http.Header{"Retry-After-Ms": []string{"6000"}},
|
||||
wantDelay: 6 * time.Second,
|
||||
wantUpstreamHint: 6 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "body seconds within budget",
|
||||
body: `{"error":{"headers":{"retry-after":"7"},"message":"Our servers are currently overloaded. Please try again later."}}`,
|
||||
wantDelay: 7 * time.Second,
|
||||
wantUpstreamHint: 7 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "body milliseconds within budget",
|
||||
body: `{"response":{"error":{"headers":{"retry-after-ms":"7000"},"message":"Our servers are currently overloaded. Please try again later."}}}`,
|
||||
wantDelay: 7 * time.Second,
|
||||
wantUpstreamHint: 7 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "exact max delay boundary still retries same account",
|
||||
headers: http.Header{"Retry-After": []string{"8"}},
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: openAIRequestScopedRetryMaxDelay,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "long http retry-after skips non-pool same-account retry",
|
||||
headers: http.Header{"Retry-After": []string{"60"}},
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: 60 * time.Second,
|
||||
wantSameAccountTry: false,
|
||||
},
|
||||
{
|
||||
name: "long event retry-after skips non-pool same-account retry",
|
||||
body: `{"type":"error","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`,
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: 315 * time.Second,
|
||||
wantSameAccountTry: false,
|
||||
},
|
||||
{
|
||||
name: "pool-mode caller retains bounded same-account retry on long hint",
|
||||
body: `{"type":"error","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`,
|
||||
callerSameAccount: true,
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: 315 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
failoverErr := newOpenAIUpstreamFailoverError(
|
||||
@@ -129,14 +191,69 @@ func TestOpenAICapacityShedHonorsRetryAfter(t *testing.T) {
|
||||
test.headers,
|
||||
[]byte(test.body),
|
||||
"Our servers are currently overloaded. Please try again later.",
|
||||
false,
|
||||
test.callerSameAccount,
|
||||
)
|
||||
require.True(t, failoverErr.RequestScopedTransient)
|
||||
require.Equal(t, test.want, failoverErr.SameAccountRetryDelay)
|
||||
require.Equal(t, test.wantDelay, failoverErr.SameAccountRetryDelay)
|
||||
require.Equal(t, test.wantUpstreamHint, failoverErr.UpstreamRetryAfter)
|
||||
require.Equal(t, test.wantSameAccountTry, failoverErr.RetryableOnSameAccount)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIStreamCapacityShedLongRetryAfterSkipsSameAccountReplay(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, passthrough := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
retryAfter string
|
||||
poolMode bool
|
||||
wantSameAccount bool
|
||||
wantHint time.Duration
|
||||
}{
|
||||
{name: "short_7s_oauth", retryAfter: "7", wantSameAccount: true, wantHint: 7 * time.Second},
|
||||
{name: "long_315s_oauth_switches", retryAfter: "315", wantSameAccount: false, wantHint: 315 * time.Second},
|
||||
{name: "long_315s_pool_keeps_retry", retryAfter: "315", poolMode: true, wantSameAccount: true, wantHint: 315 * time.Second},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("passthrough=%t/%s", passthrough, tc.name), func(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}}
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
stream := strings.Join([]string{
|
||||
"event: response.created",
|
||||
`data: {"type":"response.created","response":{"id":"resp_1"}}`,
|
||||
"",
|
||||
"event: error",
|
||||
fmt.Sprintf(`data: {"type":"error","error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":%q}}}`, tc.retryAfter),
|
||||
"",
|
||||
}, "\n")
|
||||
resp := &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{},
|
||||
Body: io.NopCloser(strings.NewReader(stream)),
|
||||
}
|
||||
account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Name: "acc"}
|
||||
if tc.poolMode {
|
||||
account.Type = AccountTypeAPIKey
|
||||
account.Credentials = map[string]any{"pool_mode": true}
|
||||
}
|
||||
var err error
|
||||
if passthrough {
|
||||
_, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "model", "model")
|
||||
} else {
|
||||
_, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "model", "model")
|
||||
}
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr)
|
||||
require.True(t, failoverErr.RequestScopedTransient)
|
||||
require.Equal(t, tc.wantSameAccount, failoverErr.RetryableOnSameAccount)
|
||||
require.Equal(t, tc.wantHint, failoverErr.UpstreamRetryAfter)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 上游降载的真实序列是「event: error → event: response.failed」。error 帧不算
|
||||
// 客户端输出:若把它当首输出 flush,clientOutputStarted 被固化,随后的 failed
|
||||
// 事件就进不了 pre-output failover 分支,只能把致命错误原样转发给客户端。
|
||||
|
||||
@@ -1922,15 +1922,20 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects(
|
||||
}
|
||||
|
||||
func openAIStreamFailedEventRetryableOnSameAccount(account *Account, payload []byte, message string) bool {
|
||||
return openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account, nil, payload, message)
|
||||
}
|
||||
|
||||
func openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account *Account, headers http.Header, payload []byte, message string) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
// 容量降载是请求级信号,不是账号级故障:上游只是让本次请求稍后再试。
|
||||
// 换账号并不改变被降载的因素(客户端身份、模型容量都与账号无关),
|
||||
// 只会让单个请求把整池账号逐个消耗掉,最终仍以同一个错误告终。
|
||||
// 因此先在同一账号上做有界重试,用尽后才按常规流程切号。
|
||||
// 容量降载是请求级信号,不是账号级故障:短时过载先在同一账号上做有界重试;
|
||||
// 若上游明确建议等待时长超过单次同号重试预算上限,非池模式单凭据账号不再盲目原地重放,直接优先尝试其他可用账号。
|
||||
if isOpenAIUpstreamCapacityShedEvent(payload) {
|
||||
return true
|
||||
upstreamRetryAfter, _ := parseUpstreamRetryAfterDelay(headers, payload)
|
||||
if openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if !account.IsPoolMode() {
|
||||
return false
|
||||
@@ -2035,7 +2040,7 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel(
|
||||
"message": message,
|
||||
},
|
||||
})
|
||||
retryableOnSameAccount := openAIStreamFailedEventRetryableOnSameAccount(account, payload, message)
|
||||
retryableOnSameAccount := openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account, headers, payload, message)
|
||||
// 流终止事件承载在 HTTP 200 内,外层响应头描述的是成功流状态,而不是语义上的
|
||||
// 429 事件。仅在配额分类时忽略这些头;故障转移错误仍保留它们,使 Retry-After
|
||||
// 和请求 ID 能继续传递给后续处理。
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -197,59 +196,19 @@ func isOpenAIRequestScopedCapacityShed(upstreamMsg string, upstreamBody []byte)
|
||||
|
||||
const openAIRequestScopedRetryMaxDelay = 8 * time.Second
|
||||
|
||||
func openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter time.Duration) bool {
|
||||
return upstreamRetryAfter <= 0 || upstreamRetryAfter <= openAIRequestScopedRetryMaxDelay
|
||||
}
|
||||
|
||||
func openAIRequestScopedRetryDelay(responseHeaders http.Header, responseBody []byte) time.Duration {
|
||||
type retryAfterValue struct {
|
||||
raw string
|
||||
milliseconds bool
|
||||
delay, ok := parseUpstreamRetryAfterDelay(responseHeaders, responseBody)
|
||||
if !ok || delay <= 0 {
|
||||
return 0
|
||||
}
|
||||
for _, value := range []retryAfterValue{
|
||||
{raw: responseHeaders.Get("Retry-After")},
|
||||
{raw: responseHeaders.Get("Retry-After-Ms"), milliseconds: true},
|
||||
{raw: gjson.GetBytes(responseBody, "error.headers.retry-after").String()},
|
||||
{raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after").String()},
|
||||
{raw: gjson.GetBytes(responseBody, "error.headers.retry-after-ms").String(), milliseconds: true},
|
||||
{raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after-ms").String(), milliseconds: true},
|
||||
} {
|
||||
raw := strings.TrimSpace(value.raw)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
var delay time.Duration
|
||||
var ok bool
|
||||
if value.milliseconds {
|
||||
delay, ok = parseOpenAIRequestScopedRetryDelayMilliseconds(raw)
|
||||
} else {
|
||||
delay, ok = parseOpenAIRequestScopedRetryDelay(raw)
|
||||
}
|
||||
if !ok || delay <= 0 {
|
||||
continue
|
||||
}
|
||||
if delay > openAIRequestScopedRetryMaxDelay {
|
||||
return openAIRequestScopedRetryMaxDelay
|
||||
}
|
||||
return delay
|
||||
if delay > openAIRequestScopedRetryMaxDelay {
|
||||
return openAIRequestScopedRetryMaxDelay
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func parseOpenAIRequestScopedRetryDelay(raw string) (time.Duration, bool) {
|
||||
if seconds, err := strconv.ParseFloat(raw, 64); err == nil && seconds > 0 {
|
||||
return time.Duration(seconds * float64(time.Second)), true
|
||||
}
|
||||
if resetAt, err := http.ParseTime(raw); err == nil {
|
||||
delay := time.Until(resetAt)
|
||||
if delay > 0 {
|
||||
return delay, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func parseOpenAIRequestScopedRetryDelayMilliseconds(raw string) (time.Duration, bool) {
|
||||
if millis, err := strconv.ParseFloat(raw, 64); err == nil && millis > 0 {
|
||||
return time.Duration(millis * float64(time.Millisecond)), true
|
||||
}
|
||||
return 0, false
|
||||
return delay
|
||||
}
|
||||
|
||||
func isOpenAIContextWindowError(upstreamMsg string, upstreamBody []byte) bool {
|
||||
@@ -388,12 +347,18 @@ func newOpenAIUpstreamFailoverError(
|
||||
retryableOnSameAccount bool,
|
||||
) *UpstreamFailoverError {
|
||||
requestScopedCapacity := isOpenAIRequestScopedCapacityShed(upstreamMsg, responseBody)
|
||||
var upstreamRetryAfter time.Duration
|
||||
if requestScopedCapacity {
|
||||
upstreamRetryAfter, _ = parseUpstreamRetryAfterDelay(responseHeaders, responseBody)
|
||||
}
|
||||
capacitySameAccountRetry := requestScopedCapacity && openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter)
|
||||
failoverErr := &UpstreamFailoverError{
|
||||
StatusCode: statusCode,
|
||||
ResponseBody: responseBody,
|
||||
ResponseHeaders: responseHeaders.Clone(),
|
||||
RetryableOnSameAccount: retryableOnSameAccount || requestScopedCapacity,
|
||||
RetryableOnSameAccount: retryableOnSameAccount || capacitySameAccountRetry,
|
||||
RequestScopedTransient: requestScopedCapacity,
|
||||
UpstreamRetryAfter: upstreamRetryAfter,
|
||||
}
|
||||
if requestScopedCapacity {
|
||||
failoverErr.SameAccountRetryDelay = openAIRequestScopedRetryDelay(responseHeaders, responseBody)
|
||||
|
||||
Reference in new issue
Block a user