From fe5e7fa404055cf03880045b4c06d5e6548991e5 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 20 Nov 2026 14:22:44 +0800 Subject: [PATCH] fix(openai): stop alpha/search tool-level 403s from benching OAuth accounts A Codex literature search (gpt-6.2-astra with literature_search_query) on a plan without that capability gets 403 {"detail":"Literature search is unavailable."} from /alpha/search. The alpha/search side-effect gate only exempted 401/404/405, so the 403 went through the generic OpenAI 403 path: the first hit cools the account for 10 minutes and three hits within 3 hours mark it errored until an admin clears it. 403 is also a failover status, so one request replays across the pool. In production, one request paused all 9 OAuth accounts within 4 seconds. On alpha/search (and the PAT Responses fallback), a 403 now writes account state only when it is an account or workspace access-state error (deactivated, disabled, ...). Every other 403 is the search tool refusing the request: the request still fails over, since another account's plan may allow it, but no account is cooled, counted or errored. --- .../internal/service/openai_alpha_search.go | 13 ++- .../service/openai_alpha_search_test.go | 105 +++++++++++++++++- 2 files changed, 110 insertions(+), 8 deletions(-) diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index ac6ed3ee21..42ba67761a 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -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 } diff --git a/backend/internal/service/openai_alpha_search_test.go b/backend/internal/service/openai_alpha_search_test.go index 378378b2fc..0de2fe3394 100644 --- a/backend/internal/service/openai_alpha_search_test.go +++ b/backend/internal/service/openai_alpha_search_test.go @@ -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) {