mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 16:04:24 +00:00
Merge pull request #8982 from Wei-Shaw/fix/openai-alpha-search-403-account-penalty
fix(openai): stop alpha/search tool-level 403s from benching OAuth accounts
This commit is contained in:
2 files changed
+110
-8
No files matched your search
@@ -100,7 +100,7 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co
|
||||
// 漏过 PAT 类型判断。这里仍允许本次请求换号,但不修改任何账号状态;
|
||||
// 真正的凭据失效由普通 Responses 请求或 whoami 校验判定。
|
||||
shouldDisable := false
|
||||
if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode) {
|
||||
if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode, upstreamMessage, respBody) {
|
||||
shouldDisable = s.handleFailoverSideEffects(ctx, resp, account, respBody, openAIAlphaSearchSchedulingModel(account, requestedModel))
|
||||
}
|
||||
retryableOnSameAccount := !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode)
|
||||
@@ -179,7 +179,7 @@ func (s *OpenAIGatewayService) forwardAlphaSearchViaResponsesWebSearch(
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
// 仍按 alpha/search 工具请求处理:PAT 的工具链路失败不能直接永久置错。
|
||||
shouldDisable := false
|
||||
if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode) {
|
||||
if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode, upstreamMessage, respBody) {
|
||||
shouldDisable = s.handleFailoverSideEffects(ctx, resp, account, respBody, openAIAlphaSearchSchedulingModel(account, requestedModel))
|
||||
}
|
||||
retryableOnSameAccount := !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode)
|
||||
@@ -540,13 +540,20 @@ func isOpenAIAlphaSearchEndpointUnsupported(account *Account, statusCode int) bo
|
||||
return statusCode == http.StatusNotFound || statusCode == http.StatusMethodNotAllowed
|
||||
}
|
||||
|
||||
func shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(statusCode int) bool {
|
||||
func shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(statusCode int, upstreamMessage string, responseBody []byte) bool {
|
||||
switch statusCode {
|
||||
case http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed:
|
||||
// 401:工具端点的 access enforcement 不代表凭据全局失效;
|
||||
// 404/405:端点不存在只说明该上游不支持独立搜索,账号本身健康。
|
||||
// 两类都只换号,不写账号错误状态。
|
||||
return false
|
||||
case http.StatusForbidden:
|
||||
// 403 只有在明确是账号/工作区访问状态错误(停用、禁用等)时才是账号级
|
||||
// 证据。其余 403 是搜索工具本身的拒绝,例如套餐不含文献检索时的
|
||||
// {"detail":"Literature search is unavailable."}:同一请求会在 failover
|
||||
// 中逐号重放,若按通用 403 处理(首次冷却 10 分钟、3 次永久置错),
|
||||
// 一条请求就能停掉整个号池。这类 403 只换号,不写账号状态。
|
||||
return isOpenAIHTTPUpstreamAccessStateError(statusCode, upstreamMessage, responseBody)
|
||||
default:
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -621,11 +621,106 @@ func TestForwardAlphaSearchOAuthNotFoundPassesThrough(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestShouldApplyOpenAIAlphaSearchAccountErrorSideEffects(t *testing.T) {
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusUnauthorized))
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusNotFound))
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusMethodNotAllowed))
|
||||
require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden))
|
||||
require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusTooManyRequests))
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusUnauthorized, "", nil))
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusNotFound, "", nil))
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusMethodNotAllowed, "", nil))
|
||||
require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusTooManyRequests, "", nil))
|
||||
|
||||
// 403:只有账号/工作区访问状态错误才写账号状态;搜索工具自身的拒绝只换号。
|
||||
literature := []byte(`{"detail":"Literature search is unavailable."}`)
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden, "Literature search is unavailable.", literature))
|
||||
require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden, "", nil))
|
||||
deactivated := []byte(`{"error":{"code":"deactivated_workspace","message":"Workspace is deactivated"}}`)
|
||||
require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden, "Workspace is deactivated", deactivated))
|
||||
}
|
||||
|
||||
// 回归:上游对文献检索返回 403 {"detail":"Literature search is unavailable."}
|
||||
// (套餐不含该能力)时,只换号,不能写账号错误状态。此前按通用 OpenAI 403
|
||||
// 处理:首次冷却 10 分钟、3 小时内 3 次永久置错,同一请求逐号重放,4 秒内
|
||||
// 停掉整个 OAuth 号池。
|
||||
func TestForwardAlphaSearchLiteratureSearchForbiddenDoesNotPenalizeAccount(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
credentials map[string]any
|
||||
wantURL string
|
||||
}{
|
||||
{
|
||||
name: "oauth",
|
||||
credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"},
|
||||
wantURL: chatgptCodexAlphaSearchURL,
|
||||
},
|
||||
{
|
||||
name: "pat responses fallback",
|
||||
credentials: map[string]any{"access_token": "at-test-token", "auth_mode": OpenAIAuthModePersonalAccessToken, "chatgpt_account_id": "chatgpt-account"},
|
||||
wantURL: chatgptCodexURL,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"id":"search-session","model":"gpt-6.2-astra","commands":{"literature_search_query":[{"q":"protein folding"}]}}`)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body))
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusForbidden,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"detail":"Literature search is unavailable."}`)),
|
||||
}}
|
||||
repo := &alphaSearchAccountStateRepo{}
|
||||
cfg := &config.Config{}
|
||||
service := &OpenAIGatewayService{
|
||||
cfg: cfg,
|
||||
httpUpstream: upstream,
|
||||
accountRepo: repo,
|
||||
rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil),
|
||||
}
|
||||
account := &Account{ID: 45, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, Credentials: tc.credentials}
|
||||
|
||||
result, err := service.ForwardAlphaSearch(context.Background(), c, account, body)
|
||||
|
||||
require.Nil(t, result)
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr, "the request may still succeed on another account")
|
||||
require.Equal(t, http.StatusForbidden, failoverErr.StatusCode)
|
||||
require.Zero(t, repo.setErrorCalls, "a tool-level 403 must not mark the account as errored")
|
||||
require.Empty(t, repo.lastError)
|
||||
require.Equal(t, tc.wantURL, upstream.lastReq.URL.String())
|
||||
require.False(t, c.Writer.Written())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 账号/工作区访问状态 403 仍是账号级证据,必须继续写账号状态。
|
||||
func TestForwardAlphaSearchAccessStateForbiddenStillMarksAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{}}`)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/alpha/search", bytes.NewReader(body))
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusForbidden,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"deactivated_workspace","message":"Workspace is deactivated"}}`)),
|
||||
}}
|
||||
repo := &alphaSearchAccountStateRepo{}
|
||||
cfg := &config.Config{}
|
||||
service := &OpenAIGatewayService{
|
||||
cfg: cfg,
|
||||
httpUpstream: upstream,
|
||||
accountRepo: repo,
|
||||
rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil),
|
||||
}
|
||||
account := &Account{ID: 46, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}}
|
||||
|
||||
_, err := service.ForwardAlphaSearch(context.Background(), c, account, body)
|
||||
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr)
|
||||
require.Equal(t, 1, repo.setErrorCalls, "a deactivated workspace is account-level evidence")
|
||||
require.Contains(t, repo.lastError, "Workspace is deactivated")
|
||||
}
|
||||
|
||||
func TestOpenAIAlphaSearchSchedulingModelUsesCanonicalAccountMapping(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user