diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 8a76f6b23c..f7322b398c 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -220,7 +220,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err) + if failoverErr.Reason != service.OpenAIAlphaSearchRejectedReason { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err) + } if c.Writer.Size() != writerSizeBeforeForward { h.handleFailoverExhausted(c, failoverErr, true) return diff --git a/backend/internal/handler/openai_alpha_search_test.go b/backend/internal/handler/openai_alpha_search_test.go new file mode 100644 index 0000000000..394447e4f3 --- /dev/null +++ b/backend/internal/handler/openai_alpha_search_test.go @@ -0,0 +1,107 @@ +package handler + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type alphaSearchUpstream struct { + service.HTTPUpstream + successAccount int64 + calls []int64 +} + +const alphaSearchSuccess = `{"output":"search result"}` + +func alphaSearchRejection(accountID int64) string { + return fmt.Sprintf(`{ "error": {"message": "rejected by %d"} }`+"\n", accountID) +} + +func (u *alphaSearchUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.calls = append(u.calls, accountID) + status, contentType, body := http.StatusBadRequest, "application/problem+json", alphaSearchRejection(accountID) + if accountID == u.successAccount { + status, contentType, body = http.StatusOK, "application/json", alphaSearchSuccess + } + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": {contentType}}, + Body: io.NopCloser(strings.NewReader(body)), + }, nil +} + +func TestAlphaSearchBadRequestFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + accountCount int + successAccount int64 + maxSwitches int + firstType string + wantCalls []int64 + wantStatus int + wantBody string + }{ + {"next account succeeds", 2, 2, 2, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusOK, alphaSearchSuccess}, + {"single account", 1, 0, 2, service.AccountTypeAPIKey, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)}, + {"all accounts reject", 2, 0, 3, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)}, + {"switch limit", 3, 3, 1, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)}, + {"oauth passes through", 2, 2, 2, service.AccountTypeOAuth, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &openAIWSFailoverHandlerAccountRepoStub{} + for i := 1; i <= tc.accountCount; i++ { + account := newPinnedCodexAccount(int64(i), service.StatusActive, true, false) + account.Concurrency = 0 + account.Credentials["pool_mode"] = true + account.Credentials["pool_mode_retry_status_codes"] = []any{400} + repo.accounts = append(repo.accounts, account) + } + if tc.firstType == service.AccountTypeOAuth { + repo.accounts[0].Type = tc.firstType + repo.accounts[0].Credentials = map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"} + } + cfg := &config.Config{RunMode: config.RunModeSimple} + upstream := &alphaSearchUpstream{successAccount: tc.successAccount} + usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 4)} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + gateway := service.NewOpenAIGatewayService(repo, usage, nil, nil, nil, nil, nil, cfg, + nil, nil, service.NewBillingService(cfg, nil), service.NewRateLimitService(repo, nil, cfg, nil, nil), billing, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil) + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, &service.APIKeyService{}, nil, nil, nil, nil, cfg) + h.maxAccountSwitches = tc.maxSwitches + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/alpha/search", strings.NewReader(`{"model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`)) + group := &service.Group{ID: 42, Platform: service.PlatformOpenAI} + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &group.ID, Group: group, User: &service.User{ID: 2}}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 2}) + + h.AlphaSearch(c) + + require.Equal(t, tc.wantCalls, upstream.calls) + require.Equal(t, tc.wantStatus, rec.Code) + require.Equal(t, tc.wantBody, rec.Body.String()) + require.Empty(t, repo.rateLimitedIDs) + if tc.wantStatus == http.StatusOK { + require.Len(t, usage.created, 1) + require.Equal(t, tc.successAccount, (<-usage.created).AccountID) + require.Equal(t, "application/json", rec.Header().Get("Content-Type")) + } else { + require.Empty(t, usage.created) + require.Equal(t, "application/problem+json", rec.Header().Get("Content-Type")) + } + }) + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 0e8c94b9f4..20132b0ea8 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3640,6 +3640,10 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted) return } + if failoverErr.Reason == service.OpenAIAlphaSearchRejectedReason && !streamStarted { + h.gatewayService.WriteAlphaSearchResponse(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody) + return + } if failoverErr.Reason == service.OpenAIResponsesToolsUnsupportedReason { // No upstream request was sent for this local capability mismatch. Keep // the original client error without attributing it to upstream health. diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index e52183ab22..aa55cc2a2e 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -18,6 +18,8 @@ import ( const ( chatgptCodexAlphaSearchURL = "https://chatgpt.com/backend-api/codex/alpha/search" openAIPlatformAlphaSearchURL = "https://api.openai.com/v1/alpha/search" + + OpenAIAlphaSearchRejectedReason GatewayFailureReason = "openai_alpha_search_rejected" ) // ForwardAlphaSearch proxies Codex standalone web search without binding the @@ -114,15 +116,24 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co } } + // API key 中转可能只拒绝独立搜索端点。上面的既有分类(访问状态、transient + // 等)保持原有副作用;其余会被直接透传的 400,除 cyber_policy 与上下文 + // 窗口超限这类请求级错误外,直接换号,不重试同一账号,也不把这次 400 + // 计入账号健康;耗尽时仍透传最后一次上游响应。 + if account.Type == AccountTypeAPIKey && resp.StatusCode == http.StatusBadRequest && + !isOpenAIAlphaSearchRequestScoped400(sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody))), respBody) { + return nil, &UpstreamFailoverError{ + StatusCode: resp.StatusCode, + ResponseBody: respBody, + ResponseHeaders: resp.Header, + Reason: OpenAIAlphaSearchRejectedReason, + } + } + if !account.IsShadow() { s.UpdateCodexUsageSnapshotFromHeaders(ctx, account.ID, resp.Header) } - writeOpenAIPassthroughResponseHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) - contentType := resp.Header.Get("Content-Type") - if contentType == "" { - contentType = "application/json" - } - c.Data(resp.StatusCode, contentType, respBody) + s.WriteAlphaSearchResponse(c, resp.StatusCode, resp.Header, respBody) if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { // 非 2xx(错误/重定向)已原样透传给客户端:不是一次成功的搜索,不计费。 return nil, nil @@ -137,6 +148,16 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co }, nil } +// WriteAlphaSearchResponse forwards the selected standalone search response, including an exhausted upstream 400. +func (s *OpenAIGatewayService) WriteAlphaSearchResponse(c *gin.Context, status int, headers http.Header, body []byte) { + writeOpenAIPassthroughResponseHeaders(c.Writer.Header(), headers, s.responseHeaderFilter) + contentType := headers.Get("Content-Type") + if contentType == "" { + contentType = "application/json" + } + c.Data(status, contentType, body) +} + func (s *OpenAIGatewayService) forwardAlphaSearchViaResponsesWebSearch( ctx context.Context, c *gin.Context, @@ -540,6 +561,15 @@ func isOpenAIAlphaSearchEndpointUnsupported(account *Account, statusCode int) bo return statusCode == http.StatusNotFound || statusCode == http.StatusMethodNotAllowed } +// isOpenAIAlphaSearchRequestScoped400 reports 400s that blame the request rather +// than the account/endpoint, which main passes through without rotating. +func isOpenAIAlphaSearchRequestScoped400(upstreamMessage string, responseBody []byte) bool { + if hit, _, _ := detectOpenAICyberPolicy(responseBody); hit { + return true + } + return isOpenAIContextWindowError(upstreamMessage, responseBody) +} + func shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(statusCode int, upstreamMessage string, responseBody []byte) bool { switch statusCode { case http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed: diff --git a/backend/internal/service/openai_alpha_search_test.go b/backend/internal/service/openai_alpha_search_test.go index 0de2fe3394..ffc6bb1104 100644 --- a/backend/internal/service/openai_alpha_search_test.go +++ b/backend/internal/service/openai_alpha_search_test.go @@ -244,7 +244,7 @@ func TestForwardAlphaSearchPATBackfillsMissingChatGPTAccountMetadata(t *testing. require.Equal(t, OpenAIAuthModePersonalAccessToken, account.Credentials["auth_mode"]) } -func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) { +func TestForwardAlphaSearchAPIKeyMapsModelAndFailsOverOnBadRequest(t *testing.T) { gin.SetMode(gin.TestMode) body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`) recorder := httptest.NewRecorder() @@ -252,13 +252,18 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) { c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body)) c.Request.Header.Set("Content-Type", "application/json") - upstreamBody := `{"error":{"type":"invalid_request_error","message":"bad search"}}` + upstreamBody := `{"error":{"type":"invalid_request_error","message":"search command is not supported by this relay"}}` upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(upstreamBody)), }} - service := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + repo := &alphaSearchAccountStateRepo{} + cfg := &config.Config{} + service := &OpenAIGatewayService{ + cfg: cfg, httpUpstream: upstream, accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil), + } account := &Account{ ID: 7, Platform: PlatformOpenAI, @@ -274,11 +279,14 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) { result, err := service.ForwardAlphaSearch(context.Background(), c, account, body) - require.NoError(t, err) - // 上游错误透传不是一次成功的搜索:不返回 result、不产生按次计费。 + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) require.Nil(t, result) - require.Equal(t, http.StatusBadRequest, recorder.Code) - require.JSONEq(t, upstreamBody, recorder.Body.String()) + require.Equal(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason) + require.Equal(t, http.StatusBadRequest, failoverErr.StatusCode) + require.Equal(t, upstreamBody, string(failoverErr.ResponseBody)) + require.False(t, c.Writer.Written()) + require.Zero(t, repo.setErrorCalls) require.Equal(t, "https://compat.example/v4/alpha/search", upstream.lastReq.URL.String()) require.Equal(t, "Bearer sk-test", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "upstream-5.6", gjson.GetBytes(upstream.lastBody, "model").String()) @@ -751,3 +759,86 @@ func TestIsOpenAIAlphaSearchEndpointUnsupported(t *testing.T) { require.False(t, isOpenAIAlphaSearchEndpointUnsupported(oauth, http.StatusNotFound)) require.False(t, isOpenAIAlphaSearchEndpointUnsupported(nil, http.StatusNotFound)) } + +func newAlphaSearchAPIKeyBadRequestFixture(t *testing.T, upstreamBody string) (*OpenAIGatewayService, *alphaSearchAccountStateRepo, *Account, *gin.Context, *httptest.ResponseRecorder, []byte) { + t.Helper() + gin.SetMode(gin.TestMode) + body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + repo := &alphaSearchAccountStateRepo{} + cfg := &config.Config{} + svc := &OpenAIGatewayService{ + cfg: cfg, httpUpstream: upstream, accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil), + } + account := &Account{ + ID: 7, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://compat.example/v4", + }, + } + return svc, repo, account, c, recorder, body +} + +func TestForwardAlphaSearchAPIKeyBadRequestAccessStateKeepsMainSideEffects(t *testing.T) { + upstreamBody := `{"error":{"code":"organization_disabled","message":"Organization has been disabled"}}` + svc, repo, account, c, _, body := newAlphaSearchAPIKeyBadRequestFixture(t, upstreamBody) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Nil(t, result) + require.NotEqual(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason, "access-state 400 must stay on the existing classification") + require.Equal(t, 1, repo.setErrorCalls, "access-state 400 must still mark the account as in main") + require.False(t, c.Writer.Written()) +} + +func TestForwardAlphaSearchAPIKeyBadRequestRequestScopedPassesThrough(t *testing.T) { + tests := []struct { + name string + body string + }{ + {"cyber_policy", `{"error":{"code":"cyber_policy","message":"blocked by cyber policy"}}`}, + {"context window exceeded", `{"error":{"code":"context_length_exceeded","message":"Your input exceeds the context window of this model"}}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc, repo, account, c, recorder, body := newAlphaSearchAPIKeyBadRequestFixture(t, tt.body) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + require.NoError(t, err, "request-scoped 400 must not rotate accounts") + require.Nil(t, result) + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.JSONEq(t, tt.body, recorder.Body.String()) + require.Zero(t, repo.setErrorCalls) + }) + } +} + +func TestForwardAlphaSearchAPIKeyBadRequestUnrecognizedFailsOverWithoutAccountState(t *testing.T) { + upstreamBody := `{"error":{"code":"unsupported_endpoint","message":"alpha search is not available"}}` + svc, repo, account, c, _, body := newAlphaSearchAPIKeyBadRequestFixture(t, upstreamBody) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Nil(t, result) + require.Equal(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason) + require.Equal(t, upstreamBody, string(failoverErr.ResponseBody)) + require.Zero(t, repo.setErrorCalls) + require.False(t, c.Writer.Written()) +}